【问题标题】:Adding prefix to string in a file为文件中的字符串添加前缀
【发布时间】:2013-08-27 20:30:57
【问题描述】:

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

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

谢谢

【问题讨论】:

  • 'Append prefix' 用语自相矛盾。

标签: python string append


【解决方案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  '

【讨论】:

    【解决方案2】:

    您快到了,但您的字符串格式错误。如您所知,5 将始终在字符串中(因为您正在添加它),您可以这样做:

    word = '5%s' % word
    

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

    word = '5' + word
    

    甚至使用str.format():

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-12
      • 2023-03-10
      • 1970-01-01
      • 2015-01-18
      • 2013-11-30
      相关资源
      最近更新 更多