在文件的字符串中添加前缀 [英] Adding prefix to string in a file

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

问题描述

好吧,我在.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.

我的代码以这样开始:

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)

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆