我有一个从用户输入收到的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'
答案 0 :(得分: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'"
答案 1 :(得分:0)
这是我的第一个堆栈溢出答案。它绝对不是最优雅的代码,但它适用于您的问题。你可以按如下方式打破这个答案:
以下是代码:
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