Python 拆分后将文本中的第一个字母大写
有没有一种简单的方法可以将字符串中“-”之后每个单词的第一个字母大写,并保持字符串的其余部分不变Python 拆分后将文本中的第一个字母大写,python,Python,有没有一种简单的方法可以将字符串中“-”之后每个单词的第一个字母大写,并保持字符串的其余部分不变 x="hi there-hello world from Python - stackoverflow" 预期产量为 x="Hi there-Hello world from Python - Stackoverflow" 我尝试的是: "-".join([i.title() for i in x.split("-")]) #this capitalize the first letter in
x="hi there-hello world from Python - stackoverflow"
预期产量为
x="Hi there-Hello world from Python - Stackoverflow"
我尝试的是:
"-".join([i.title() for i in x.split("-")]) #this capitalize the first letter in each word; what I want is only the first word after split
注意:“-”并不总是被空格包围试试这个:
"-".join([i.capitalize() for i in x.split("-")])
可以使用正则表达式执行此操作:
import re
x = "hi there-hello world from Python - stackoverflow"
y = re.sub(r'(^|-\s*)(\w)', lambda m: m.group(1) + m.group(2).upper(), x)
print(y)
基本上是@Milad Barazandeh所做的,但却是另一种方式
answer=“-”.join([i[0].upper()+i[1:]表示x.split(“-”)中的i)