s = 'the brown fox'

...在这里做点什么……

S应为:

'The Brown Fox'

最简单的方法是什么?


当前回答

以防你想裁员

# 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.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'

在Python中,您可以使用title()方法将字符串中的每个单词大写:

string = "this is a test string"
capitalized_string = string.title()
print(capitalized_string)

输出:

This Is A Test String

如果你只想知道第一个字母:

>>> 'hello world'.capitalize()
'Hello world'

但是每个单词都要大写:

>>> 'hello world'.title()
'Hello World'

对你的问题最简单的解决方法,在我的情况下是有效的:

import string
def solve(s):
    return string.capwords(s,' ') 
    
s=input()
res=solve(s)
print(res)

我非常喜欢这个答案:

复制粘贴版本的@jibberia回答:

def capitalize(line):
    return ' '.join([s[0].upper() + s[1:] for s in line.split(' ')])

但是我发送的一些行分离了一些空白的“字符,在尝试执行s[1:]时导致错误。可能有更好的方法,但我必须添加一个if len(s)>0,就像在

return ' '.join([s[0].upper() + s[1:] for s in line.split(' ') if len(s)>0])