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

2024-04-27 05:03:04 发布

您现在位置: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 each word; what I want is only the first word after split

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


Tags: the方法字符串infromhelloworld字母
3条回答

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

  • answer = "-".join([i[0].upper() + i[1:] for i in x.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)

相关问题 更多 >