s = 'the brown fox'
...在这里做点什么……
S应为:
'The Brown Fox'
最简单的方法是什么?
s = 'the brown fox'
...在这里做点什么……
S应为:
'The Brown Fox'
最简单的方法是什么?
当前回答
在Python中,您可以使用title()方法将字符串中的每个单词大写:
string = "this is a test string"
capitalized_string = string.title()
print(capitalized_string)
输出:
This Is A Test String
其他回答
复制粘贴版本的@jibberia回答:
def capitalize(line):
return ' '.join(s[:1].upper() + s[1:] for s in line.split(' '))
尽管所有的答案都是令人满意的,但我将尝试涵盖两个额外的情况以及所有前面的情况。
如果空间不均匀,你想保持不变
string = hello world i am here.
如果所有的字符串不是从字母开始
string = 1 w 2 r 3g
在这里你可以使用这个:
def solve(s):
a = s.split(' ')
for i in range(len(a)):
a[i]= a[i].capitalize()
return ' '.join(a)
这将给你:
output = Hello World I Am Here
output = 1 W 2 R 3g
以防你想裁员
# Assuming you are opening a new file
with open(input_file) as file:
lines = [x for x in reader(file) if x]
# for loop to parse the file by line
for line in lines:
name = [x.strip().lower() for x in line if x]
print(name) # Check the result
大写的单词…
str = "this is string example.... wow!!!";
print "str.title() : ", str.title();
@Gary02127评论,下面的解决方案适用于带有撇号的标题
import re
def titlecase(s):
return re.sub(r"[A-Za-z]+('[A-Za-z]+)?", lambda mo: mo.group(0)[0].upper() + mo.group(0)[1:].lower(), s)
text = "He's an engineer, isn't he? SnippetBucket.com "
print(titlecase(text))
建议的str.title()方法并非在所有情况下都有效。 例如:
string = "a b 3c"
string.title()
> "A B 3C"
而不是"A B 3c"
我认为,最好这样做:
def capitalize_words(string):
words = string.split(" ") # just change the split(" ") method
return ' '.join([word.capitalize() for word in words])
capitalize_words(string)
>'A B 3c'