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

sca*_*ous 0 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
Run Code Online (Sandbox Code Playgroud)

好吧,我真的不知道如何附加前缀5,然后用7位数字和5前缀覆盖7位数字.我试了几件但都失败了:/

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

谢谢

Ter*_*ryA 5

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

word = '5%s' % word
Run Code Online (Sandbox Code Playgroud)

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

word = '5' + word
Run Code Online (Sandbox Code Playgroud)

甚至使用str.format():

word = '5{}'.format(word)
Run Code Online (Sandbox Code Playgroud)