2024-04-25 10:03:57 发布
网友
例如,这句话:
say "mosquito!"
我尝试用以下代码大写:
'say "mosquito!"'.capitalize()
返回以下内容:
'Say "mosquito!"’
然而,期望的结果是:
'Say "Mosquito!"’
这是相当棘手的。我要找一个单词的第一个字母。将字符串拆分为单词,并在将每个单词的第一个字母转换为大写后再次连接它们。你知道吗
def start(word): for n in range(len(word)): if word[n].isalpha(): return n return 0 strng = 'say mosquito\'s house' print( ' '.join(word[:start(word)] + word[start(word)].upper() + word[start(word)+1:] for word in strng.split()))
结果:
Say "Mosquito's House"
您可以使用str.title:
str.title
print('say "mosquito!"'.title()) # Output: Say "Mosquito!"
看起来Python有一个内置的方法!你知道吗
可以在正则表达式替换中使用lambda:
string = 'say "mosquito\'s house" ' import re caps = re.sub("((^| |\")[a-z])",lambda m:m.group(1).upper(),string) # 'Say "Mosquito\'s House" '
这是相当棘手的。我要找一个单词的第一个字母。将字符串拆分为单词,并在将每个单词的第一个字母转换为大写后再次连接它们。你知道吗
结果:
您可以使用
str.title
:看起来Python有一个内置的方法!你知道吗
可以在正则表达式替换中使用lambda:
相关问题 更多 >
编程相关推荐