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

Python: Convert entire string to lowercase except for substrings in quotes

我从用户输入中收到了一个 python 字符串。

假设用户输入是这样的:

 I am Enrolled in a course, 'MPhil' since 2014. I LOVE this 'SO MuCH'

如果这个字符串存储在一个名为 input_string 的变量中,并且我在其上应用 .lower(),它会将整个字符串转换为小写。

input_string = input_string.lower()

结果:

i am enrolled in a course, 'mphil' since 2014. i love this 'so much'

这是我希望小写字母执行的操作: 将所有内容(引号中的内容除外)转换为小写。

i am enrolled in a course, 'MPhil' since 2014. i love this 'SO MuCH'

我们可以结合使用否定前瞻、后视、应用词边界和使用替换函数:

>>> 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'"

这是我的第一个堆栈溢出答案。它绝对不是最优雅的代码,但它适用于您的问题。您可以按如下方式分解此答案:

  1. 将字符串拆分为列表
  2. 创建两个子列表
  3. 将所需的子列表转换为较低的
  4. 连接子列表
  5. 在列表中用join方法打印

代码如下:

string = "I am Enrolled in a course, 'MPhil' since 2014. I LOVE this 'SO MuCH'"  
l = string.split()    #split string to list
lower_l = l[0:11]       
unchanged_l = l[11:]  #create sub-lists with split at 11th element
lower_l = [item.lower() for item in lower_l]    #convert to lower
l = lower_l + unchanged_l    #concatenate
print ' '.join(l)     #print joined list delimited by space

对于示例字符串和在单引号之间包含任意数量单词的字符串,您可以使用此正则表达式模式来解决此问题。

import re
pat = re.compile(r"(^|' )([\w .,]+)($| ')") 

input_string_1 = "I am Enrolled in a course, 'MPhil' since 2014. I LOVE this 'SO MuCH'"
input_string_2 = "I am Enrolled in a course, 'MPhil' since 2014. I LOVE this 'SO SO MuCH'"

output_string_1 = pat.sub(lambda match: match.group().lower(), input_string_1)
output_string_2 = pat.sub(lambda match: match.group().lower(), input_string_2)

print(input_string_1)
print(output_string_1)
print(input_string_2)
print(output_string_2)