首页 > 解决方案 > 如何在 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)

标签: python

解决方案


使用具有忽略大小写的方法和选项的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'

推荐阅读