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

如何用python编写程序,用其他字符替换字符串中的字符,而不考虑大小写字母,python,Python,我要这个程序忽略案例信 例如,对于字符串“Apple”,可以用任何其他字符替换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(

我要这个程序忽略案例信 例如,对于字符串“Apple”,可以用任何其他字符替换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)

尝试使用ascii数字。大写和小写的代码之间的区别是32

关于python中不区分大小写的字符串替换的堆栈溢出有多篇文章,但几乎所有的文章都涉及使用正则表达式。例如,请参见

依我看,在这种情况下最简单的事情就是调用str.replace两次。首先更换大写版本,然后更换小写版本

以下是一个例子:

text = "Apple"
to_repl = "a"
repl_with = "B"
print(text.replace(to_repl.upper(), repl_with).replace(to_repl.lower(), repl_with))
#Bpple
使用重新标准库,该库具有子方法和忽略大小写选项。使用起来也很方便。这适用于您的示例:

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'

text.replace.upper、replace_和.replace.lower、replace_和?^^^^这就是为什么我们不使用python内置变量名的原因。谢谢您的帮助!我在想,如果不使用内置函数,还有其他方法吗。就像编写我们自己的算法来解决一个特定的问题,而不需要任何内置函数的帮助。还是感谢你的回答!谢谢:@ManishGupta似乎你想避免调用str.replace-你可以这样做:。加入[t如果t不在[to_repl.lower,to_repl.upper]否则在文本中用for t repl_]耶!我是新来的,也不熟悉python语言。我一直在努力编写自己的算法,但没有使用内置函数。没问题,只要记住保持它的简单和可用性:如果你想学习Python的禅,你可以导入它。顺便说一句,万一你错过了,我试过,也用ascii码在网上搜索解决方案,但没有得到答案。