python - 如何在 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)
解决方案
使用具有忽略大小写的方法和选项的re
标准库。sub
使用起来也很方便。这适用于您的示例:
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'
推荐阅读
- ios - 在 Swift 中使用 Date 检查新月份
- android - 如何从数据列表中的键中获取子对象的值(在firebase中使用childeventlistener:android studio)
- mysql - mySQL WorkBench 脚本外壳无响应
- r - 将命名列表的名称和值组合成字符串的更好方法
- ibm-mobilefirst - 使用访问令牌的 HTTPRequest 在 IBM Mobilefirst 8.0.0 中调用资源时出错
- discord.js - 如何进行设置命令 [discord.js]
- android - 如何在空对象引用上解决此问题
- c# - 我如何循环对象数组并使用 Linq 将每个对象的属性添加到变量中?
- c - 如何使用C在netfilter中打印特定IP地址的数据包信息?
- android-emulator - 运行android模拟器后其他程序出现延迟