用str.replace()替换数字 [英] Replacing digits with str.replace()

查看:393
本文介绍了用str.replace()替换数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我想通过用%d替换数字来创建新字符串:

I want to make a new string by replacing digits with %d for example:

Name.replace( "_u1_v1" , "_u%d_v%d") 

...但是数字1可以是任何数字,例如"_u2_v2.tx"

...but the number 1 can be any digit for example "_u2_v2.tx"

我可以给通配符replace()期望任何数字吗?就像"_u"%d"_v"%d".tx"

Can I give replace() a wildcard to expect any digit? Like "_u"%d"_v"%d".tx"

还是我必须做一个正则表达式?

Or do I have to make a regular expression?

推荐答案

使用正则表达式:

>>> import re
>>> s = "_u1_v1"
>>> print re.sub('\d', '%d', s)
_u%d_v%d

\d匹配任何数字0-9. re.sub%d

\d matches any number 0-9. re.sub replaces the number(s) with %d

这篇关于用str.replace()替换数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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