Adding Prefix To String In A File
Well i have a sort of telephone directory in a .txt file, what i want to do is find all the numbers with this pattern e.g. 829-2234 and append the number 5 to the beginning of the
Solution 1:
You're almost there, but you got your string formatting the wrong way. As you know that 5
will always be in the string (because you're adding it), you do:
word = '5%s' % word
Note that you can also use string concatenation here:
word = '5' + word
Or even use str.format()
:
word = '5{}'.format(word)
Solution 2:
If you're doing it with regex then use re.sub
:
>>>strs = "829-2234 829-1000 111-2234 ">>>regex = re.compile(r"\b(\d{3}-\d{4})\b")>>>regex.sub(r'5\1', strs)
'5829-2234 5829-1000 5111-2234 '
Post a Comment for "Adding Prefix To String In A File"