Python 将字符串中单词的第一个字符大写
我有如下字符串:我尝试过.title()和capitalize(),但没有成功 输入 输出Python 将字符串中单词的第一个字符大写,python,python-2.7,Python,Python 2.7,我有如下字符串:我尝试过.title()和capitalize(),但没有成功 输入 输出 "Hello World" "1hello World" "Hello World Lol" "1 2 2 3 4 5 6 7 8 9" "1 W 2 R 3g" "132 456 Wq M E" "Q W E R T Y U I O P A S D F G H J K L Z X C V B N M Q W E R T Y U I O P A S D F G H J K L Z X C V
"Hello World"
"1hello World"
"Hello World Lol"
"1 2 2 3 4 5 6 7 8 9"
"1 W 2 R 3g"
"132 456 Wq M E"
"Q W E R T Y U I O P A S D F G H J K L Z X C V B N M Q W E R T Y U I O P A S D F G H J K L Z X C V B N M"
我也尝试过这个方法,但当输入的字符串超过一个空格时,它就会出错
str = "Hello World Lol"
for i in range(0,len(new)):
str += new[i][0].upper() + new[i][1:] + " "
print str
您如何尝试
.title()
str.title()
string1 = "hello world lol"
string2 = string1.title()
您如何尝试.title()
str.title()
string1 = "hello world lol"
string2 = string1.title()
在您的上下文中,可以使用capitalize()
方法
str = "Helo w world lol"
lista = []
for i in str.split(" "):
lista.append(i.capitalize())
print " ".join(lista) #"Helo W World Lol"
使用列表理解:
print " ".join([i.capitalize() for i in str.split(" ")])
在您的上下文中,可以使用capitalize()
方法
str = "Helo w world lol"
lista = []
for i in str.split(" "):
lista.append(i.capitalize())
print " ".join(lista) #"Helo W World Lol"
使用列表理解:
print " ".join([i.capitalize() for i in str.split(" ")])
例如,您想做什么?当我在我的机器上执行“hello world”.title()
时,我会得到“hello world”
。这不是你得到的吗?你得到了什么?您正在分配或显示结果,对吗?请注意,字符串是不可变的,因此如果您这样做s=“hello world”;s、 title();打印
,它仍将打印未资本化的版本。为什么.title()
不起作用?有什么不同吗?可能重复的.title()
也适用于我。我不知道作者为什么不知道。你想做什么?当我在我的机器上做“hello world”.title()
,我会得到“hello world”
。这不是你得到的吗?你得到了什么?您正在分配或显示结果,对吗?请注意,字符串是不可变的,因此如果您这样做s=“hello world”;s、 title();打印
,它仍将打印未资本化的版本。为什么.title()
不起作用?有什么不同吗?可能重复的.title()
也适用于我。不知道作者为什么不知道。它在“1hello world”中不起作用我需要输出“1hello world”它在“1hello world”中不起作用我需要输出“1hello world”