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

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

本文介绍了为文件中的字符串添加前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 numbers.

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

so the result now becomes 5829-2234.

我的代码是这样开始的:

my code begins like this:

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,然后用 5 前缀的 7 位数字覆盖 7 位数字.我尝试了几件事,但都失败了:/

well i don't really know how to append the prefix 5 and then overwrite the 7-digit number with 7-digit number with 5 prefix. I tried a few things but all failed :/

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

Any tip/help would be greatly appreciated :)

谢谢

推荐答案

您快完成了,但是您的字符串格式设置错误.如您所知 5 将始终在字符串中(因为您正在添加它),您可以:

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

甚至使用str.format():

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

这篇关于为文件中的字符串添加前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 00:28