如何用python编写程序,将字符串中的字符替换为其他字符,而不考虑大小写字母



我希望这个程序忽略大小写例如,对于字符串"Apple","A"或"A"可以将Apple中的"A"替换为任何其他字符。

store = []
def main(text=input("Enter String: ")):
replace = input("Enter the replace char: ")
replace_with = input("Enter the replace with char: ")
for i in text:
store.append(i)

main()
print(store)  # printing the result here
f_result = ''.join(store)  # Joining back to original state 
print(f_result)

使用具有sub方法和忽略大小写选项的re标准库。使用起来也很方便。这适用于您的示例:

import re
def main(text=input("Enter String: ")):
replace = input("Enter the replace char: ")
replace_with = input("Enter the replace with char: ")
return re.sub(replace, replace_with, text, flags=re.IGNORECASE)
main()
>>Enter String: Apple
>>Enter the replace char: a
>>Enter the replace with char: B
>>'Bpple'

尝试使用ascii数字。大写字母和小写字母的代码之间的差异是32

Stack Overflow上有多篇关于python中不区分大小写的字符串替换的帖子,但几乎所有帖子都涉及使用正则表达式。(例如,请参阅本文。(

IMO,在这种情况下最简单的事情是对str.replace进行2次呼叫。首先更换大写版本,然后更换小写版本。

这里有一个例子:

text = "Apple"
to_repl = "a"
repl_with = "B"
print(text.replace(to_repl.upper(), repl_with).replace(to_repl.lower(), repl_with))
#Bpple

相关内容

最新更新