Python:将整个字符串转换为小写,但引号中的子字符串除外

use*_*637 0 python string lowercase

我有一个从用户输入收到的python字符串.

假设用户输入是这样的:

 I am Enrolled in a course, 'MPhil' since 2014. I LOVE this 'SO MuCH'
Run Code Online (Sandbox Code Playgroud)

如果此字符串存储在名为input_string的变量中,并且我对其应用.lower(),则会将整个事物转换为小写.

input_string = input_string.lower()
Run Code Online (Sandbox Code Playgroud)

结果:

i am enrolled in a course, 'mphil' since 2014. i love this 'so much'
Run Code Online (Sandbox Code Playgroud)

这就是我希望小写的内容:将除引号之外的所有内容转换为小写.

i am enrolled in a course, 'MPhil' since 2014. i love this 'SO MuCH'
Run Code Online (Sandbox Code Playgroud)

ale*_*cxe 5

我们可以使用负前瞻,后瞻,应用单词边界和使用替换函数的组合:

>>> s = "I am Enrolled in a course, 'MPhil' since 2014. I LOVE this 'SO MuCH'"
>>> re.sub(r"\b(?<!')(\w+)(?!')\b", lambda match: match.group(1).lower(), s)
"i am enrolled in a course, 'MPhil' since 2014. i love this 'SO MuCH'"
Run Code Online (Sandbox Code Playgroud)

  • “SO MuCH MPhil”可能会失败吗? (2认同)
  • 希望将 'SO MuCH MPhil' 保留为 ''SO MuCH MPhil',无需更改大小写,因为整个内容都在引号之间 (2认同)