Python section string with regular expressions

I am trying to clear text strings using Python section and regular expressions. For example:

testString = 'Tre Bröders Väg 6 2tr'
sep = '[0-9]tr'
head,sep,tail = testString.partition(sep)
head
>>>'Tre Br\xc3\xb6ders V\xc3\xa4g 6 2tr'

The head still contains 2tr that I want to delete. Am I not so good with regex, but shouldn't [0-9] do the trick?

The result that I would expect from this example would be

head
>>> 'Tre Br\xc3\xb6ders V\xc3\xa4g 6
+4
source share
1 answer

str.partitiondoes not support regular expression, therefore, when you give it a string like - '[0-9]tr', it tries to find this exact string in testStringfor partition based, it does not use any regular expression.

According to the documentation str.partition-

sep 3-, , . , 3-, , .

, head, re.split() re, maxsplit, 1, , , str.partition. -

import re
testString = 'Tre Bröders Väg 6 2tr'
sep = '[0-9]tr'
head = re.split(sep,testString,1)[0]

-

>>> import re
>>> testString = 'Tre Bröders Väg 6 2tr'
>>> sep = '[0-9]tr'
>>> head = re.split(sep,testString,1)[0]
>>> head
'Tre Bröders Väg 6 '
+2

Source: https://habr.com/ru/post/1609087/


All Articles