如何替换字符串中的数字?

1 投票
3 回答
2715 浏览
提问于 2025-04-16 04:23

好吧,假设我在Python里有一个字符串:

str="martin added 1 new photo to the <a href=''>martins photos</a> album."

在实际应用中,这个字符串包含了很多CSS/HTML内容

我想最快的方式把里面的数字1('1 new photo')改成比如说'2 new photos'。当然,后面这个'1'可能会变成'12'。需要注意的是,我不知道这个数字是什么,所以直接替换是不行的。

我还需要把'photo'改成'photos',不过我可以直接用a .replace(...)来做。除非有更简单、更整洁的方法来同时修改这两个内容?

3 个回答

2

因为你不需要解析HTML,所以直接用正则表达式就行了。

import re

exp = "{0} added ([0-9]*) new photo".format(name)
number = int(re.findall(exp, strng)[0])

这假设你总是会传入一个包含数字的字符串。如果不是,你会遇到IndexError的错误。

我建议你除了存储格式化后的字符串外,还要存储数字和格式字符串。当数字变化时,重新生成格式字符串,并替换掉你存储的那个副本。这样做会比试图解析字符串来获取数字要好得多。

关于你问的HTML是否重要,我觉得不重要。因为你并不是在提取HTML编码的信息,所以你并不是在用正则表达式解析HTML。从这个角度来看,这只是一个字符串。

3

更新

没关系。从评论中可以看出,提问者的需求比问题表面上看起来要复杂得多。我觉得我的回答可能无法解决这个问题。

原始回答

你可以把字符串转换成一个模板并保存。用占位符来表示变量。

template = """%(user)s added %(count)s new %(l_object)s to the 
      <a href='%(url)s'>%(text)s</a> album."""

options = dict(user = "Martin", count = 1, l_object = 'photo', 
      url = url, text = "Martin's album")

print template % options

这个方法要求句子的对象在外部进行复数处理。如果你想在你的模板中实现这个逻辑(或者更复杂的条件),你可以考虑使用一些模板引擎,比如JinjaCheetah

2

听起来这就是你想要的(不过为什么想要这个又是另一个问题 :^)

import re

def add_photos(s,n):
    def helper(m):
        num = int(m.group(1)) + n
        plural = '' if num == 1 else 's'
        return 'added %d new photo%s' % (num,plural)
    return re.sub(r'added (\d+) new photo(s?)',helper,s)

s = "martin added 0 new photos to the <a href=''>martins photos</a> album."
s = add_photos(s,1)
print s
s = add_photos(s,5)
print s
s = add_photos(s,7)
print s

输出

martin added 1 new photo to the <a href=''>martins photos</a> album.
martin added 6 new photos to the <a href=''>martins photos</a> album.
martin added 13 new photos to the <a href=''>martins photos</a> album.

撰写回答