s = 'the brown fox'
...在这里做点什么……
S应为:
'The Brown Fox'
最简单的方法是什么?
s = 'the brown fox'
...在这里做点什么……
S应为:
'The Brown Fox'
最简单的方法是什么?
当前回答
.title()方法不能很好地工作,
>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"
试试string.capwords()方法,
import string
string.capwords("they're bill's friends from the UK")
>>>"They're Bill's Friends From The Uk"
来自Python capwords文档:
使用str.split()将参数拆分为单词,使用str.capitalize()将每个单词大写,并使用str.join()连接大写的单词。如果可选的第二个参数sep不存在或为None,则空白字符的运行将被单个空格替换,并且前导和尾部的空白将被删除,否则sep用于分隔和连接单词。
其他回答
只是因为这类事情对我来说很有趣,这里还有两个解决方案。
拆分为单词,从拆分的组中为每个单词加首字母大写,然后重新连接。这将把分隔单词的空白改为一个单独的空白,不管它是什么。
s = 'the brown fox'
lst = [word[0].upper() + word[1:] for word in s.split()]
s = " ".join(lst)
编辑:我不记得当我写上面的代码时我在想什么,但是没有必要构建一个显式的列表;我们可以使用生成器表达式以惰性方式来执行此操作。所以这里有一个更好的解决方案:
s = 'the brown fox'
s = ' '.join(word[0].upper() + word[1:] for word in s.split())
Use a regular expression to match the beginning of the string, or white space separating words, plus a single non-whitespace character; use parentheses to mark "match groups". Write a function that takes a match object, and returns the white space match group unchanged and the non-whitespace character match group in upper case. Then use re.sub() to replace the patterns. This one does not have the punctuation problems of the first solution, nor does it redo the white space like my first solution. This one produces the best result.
import re
s = 'the brown fox'
def repl_func(m):
"""process regular expression match groups for word upper-casing problem"""
return m.group(1) + m.group(2).upper()
s = re.sub("(^|\s)(\S)", repl_func, s)
>>> re.sub("(^|\s)(\S)", repl_func, s)
"They're Bill's Friends From The UK"
我很高兴我研究了这个答案。我不知道re.sub()可以接受函数!您可以在re.sub()中进行非平凡的处理以产生最终结果!
对你的问题最简单的解决方法,在我的情况下是有效的:
import string
def solve(s):
return string.capwords(s,' ')
s=input()
res=solve(s)
print(res)
在Python中,您可以使用title()方法将字符串中的每个单词大写:
string = "this is a test string"
capitalized_string = string.title()
print(capitalized_string)
输出:
This Is A Test String
尽管所有的答案都是令人满意的,但我将尝试涵盖两个额外的情况以及所有前面的情况。
如果空间不均匀,你想保持不变
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
如果你只想知道第一个字母:
>>> 'hello world'.capitalize()
'Hello world'
但是每个单词都要大写:
>>> 'hello world'.title()
'Hello World'