I have a list containing several strings. I want to capitalize the first letter of each string in the list. How can I do it using list methods? Or I have to use regex here?
我有一个包含几个字符串的列表。我想大写列表中每个字符串的第一个字母。我怎么能用list方法呢?或者我必须在这里使用正则表达式?
2 个解决方案
#1
1
Just call capitalize
on each string. Note that it lowercases the rest of the letters
只需调用每个字符串。请注意,它会降低其余字母的大小
l = ['This', 'is', 'a', 'list']
print [x.capitalize() for x in l]
['This', 'Is', 'A', 'List']
If you need to preserve case on the other letters, do this instead
如果您需要在其他字母上保留大小写,请改为使用
l = ['This', 'is', 'a', 'list', 'BOMBAST']
print [x[0].upper() + x[1:] for x in l]
['This', 'Is', 'A', 'List', 'BOMBAST']
#2
0
x=['a', 'test','string']
print [a.title() for a in x]
['A', 'Test', 'String']
['A','测试','字符串']
Since regex
is tagged too, you can use something like following
由于正则标记也被标记,您可以使用以下内容
>>> import re
>>> x=['a', 'test','string']
>>> def repl_func(m):
return m.group(1) + m.group(2).upper()
>>> [re.sub("(^|\s)(\S)", repl_func, a) for a in x]
['A', 'Test', 'String']
#1
1
Just call capitalize
on each string. Note that it lowercases the rest of the letters
只需调用每个字符串。请注意,它会降低其余字母的大小
l = ['This', 'is', 'a', 'list']
print [x.capitalize() for x in l]
['This', 'Is', 'A', 'List']
If you need to preserve case on the other letters, do this instead
如果您需要在其他字母上保留大小写,请改为使用
l = ['This', 'is', 'a', 'list', 'BOMBAST']
print [x[0].upper() + x[1:] for x in l]
['This', 'Is', 'A', 'List', 'BOMBAST']
#2
0
x=['a', 'test','string']
print [a.title() for a in x]
['A', 'Test', 'String']
['A','测试','字符串']
Since regex
is tagged too, you can use something like following
由于正则标记也被标记,您可以使用以下内容
>>> import re
>>> x=['a', 'test','string']
>>> def repl_func(m):
return m.group(1) + m.group(2).upper()
>>> [re.sub("(^|\s)(\S)", repl_func, a) for a in x]
['A', 'Test', 'String']