繁体   English   中英

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

[英]How can I write a program in python to replace character in string with other character irrespective of case-letter

我希望该程序忽略字符串'Apple'的大小写字母Eg,例如'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'

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

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

IMO,在这种情况下最简单的事情是对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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM