在文件中为字符串添加前缀

时间:2013-08-25 04:27:20

标签: python string append

我在.txt文件中有一种电话簿, 我想要做的是找到这种模式的所有数字,例如829-2234并将数字5附加到数字的开头。

所以结果现在变成了5829-2234。

我的代码开头是这样的:

import os
import re
count=0

#setup our regex
regex=re.compile("\d{3}-\d{4}\s"}

#open file for scanning
f= open("samplex.txt")

#begin find numbers matching pattern
for line in f:
    pattern=regex.findall(line)
    #isolate results
    for word in pattern:
        print word
        count=count+1 #calculate number of occurences of 7-digit numbers
# replace 7-digit numbers with 8-digit numbers
        word= '%dword' %5

我真的不知道如何附加前缀5,然后用7位数字和5前缀覆盖7位数字。我尝试了一些但都失败了:/

任何提示/帮助将不胜感激:)

由于

2 个答案:

答案 0 :(得分:5)

你几乎就在那里,但你的字符串格式错误。如您所知5将始终在字符串中(因为您正在添加它),您可以:

word = '5%s' % word

请注意,您也可以在此处使用字符串连接:

word = '5' + word

甚至可以使用str.format()

word = '5{}'.format(word)

答案 1 :(得分:1)

如果您正在使用正则表达式,请使用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  '