Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 拆分后将文本中的第一个字母大写_Python - Fatal编程技术网

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)

可能重复@JimG。如果我删除了问题,该问题将返回标题大小写中的字符串。