拆分后文本中第一个字母的大写字母



有没有一种简单的方法可以将字符串中"-"后每个单词的第一个字母大写,并保持字符串的其余部分不变?

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

注意:"-"并不总是被空格包围

您可以使用正则表达式:

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)

试试这个:

"-".join([i.capitalize() for i in x.split("-")])

基本上是@Milad Barazandeh所做的,但的另一种方法

  • answer = "-".join([i[0].upper() + i[1:] for i in x.split("-")])

相关内容

最新更新