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

编程入门 行业动态 更新时间:2024-10-28 14:36:38
本文介绍了在文件的字符串中添加前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

好吧,我在.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=repile("\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)

更多推荐

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

本文发布于:2023-10-16 17:09:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1498205.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:前缀   字符串   文件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!