Python字符串替换只使用一行代码(用“*”替换“H”和“h”)

问题描述 投票:-2回答:3

Python:在字符串“你好,你好吗?” ,我怎么能用“*”代替“H”和“h”?我只想在一行代码中做到这一点......

python-3.x string str-replace
3个回答
0
投票

您可以使用re,例如:

import re
old_text="Hello, how are you?"
new_text = re.sub(r'h', '2', old_text, flags=re.IGNORECASE)
print (new_text)

0
投票

使用正则表达式:

import re
s = "Hello, how are you?"
s_replaced = re.sub('(H|h)', '*', s)

你可以查看正则表达式的解释here


0
投票

有一些方法可以做到这一点:

您可以在操作时多次链接.replace()并返回一个字符串:

>>> print('Hello, how are you?'.replace('H', '*').replace('h', '*'))
*ello, *ow are you?

或者使用正则表达式:

>>> import re
>>> re.sub('[Hh]', '*', 'Hello, how are you?')
'*ello, *ow are you?'
© www.soinside.com 2019 - 2024. All rights reserved.