用 x 替换字符串中的整数而不进行错误处理 [英] replacing the integers in a string with x's without error handling

查看:34
本文介绍了用 x 替换字符串中的整数而不进行错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试找出一种简单的方法来用 python 中的 x 替换字符串中的整数.通过执行以下操作,我可以解决问题:

I have been trying to figure out a simple way to replace the integers within a string with x's in python. I was able to get something ok by doing the following:

In [73]: string = "martian2015"
In [74]: string = list(string)

In [75]: for n, i in enumerate(string):
   ....:     try:
   ....:         if isinstance(int(i), int):
   ....:             string[n]='x'
   ....:     except ValueError:
   ....:         continue

这实际上会产生如下结果:

This actually yields something like the following:

In [81]: string
Out[81]: ['m', 'a', 'r', 't', 'i', 'a', 'n', 'x', 'x', 'x', 'x']
In [86]: joiner = ""

In [87]: string = joiner.join(string)

In [88]: string
Out[88]: 'martianxxxx'

我的问题是:有没有办法以更简单的方式获得结果而不依赖错误/异常处理?>

My question is: is there any way of getting the result in a simpler manner without relying on error/exception handling?

推荐答案

是的,使用正则表达式和 重新模块:

Yes, using regex and the re module:

import re

new_string = re.sub("\d", "x", "martin2015")

字符串 "\d" 告诉 Python 搜索字符串中的所有数字.第二个参数是您要替换所有匹配项的内容,第三个参数是您的输入.(re.sub 代表替代")

The string "\d" tells Python to search for all digits in the string. The second argument is what you want to replace all matches with, and the third argument is your input. (re.sub stands for "substitute")

这篇关于用 x 替换字符串中的整数而不进行错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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