import res = '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"
def capitalize_words(string):words = string.split(" ") # just change the split(" ") methodreturn ' '.join([word.capitalize() for word in words])
capitalize_words(string)>'A B 3c'
"" => """a b c" => "A B C""foO baR" => "FoO BaR""foo bar" => "Foo Bar""foo's bar" => "Foo's Bar""foo's1bar" => "Foo's1bar""foo 1bar" => "Foo 1bar"
将句子分成单词并将第一个字母大写,然后将其连接在一起:
# Be careful with multiple spaces, and empty strings# for empty words w[0] would cause an index error,# but with w[:1] we get an empty string as desireddef cap_sentence(s):return ' '.join(w[:1].upper() + w[1:] for w in s.split(' '))
无需拆分字符串,检查空格以查找单词的开头
def cap_sentence(s):return ''.join( (c.upper() if i == 0 or s[i-1] == ' ' else c) for i, c in enumerate(s) )
或者使用发电机:
# Iterate through each of the characters in the string# and capitalize the first char and any char after a blank spacefrom itertools import chaindef cap_sentence(s):return ''.join( (c.upper() if prev == ' ' else c) for c, prev in zip(s, chain(' ', s)) )
# match the beginning of the string or a space, followed by a non-spaceimport redef cap_sentence(s):return re.sub("(^|\s)(\S)", lambda m: m.group(1) + m.group(2).upper(), s)
# Assuming you are opening a new filewith open(input_file) as file:lines = [x for x in reader(file) if x]
# for loop to parse the file by linefor line in lines:name = [x.strip().lower() for x in line if x]print(name) # Check the result
Python 3.6.9 (default, Nov 7 2019, 10:44:02)[GCC 8.3.0] on linuxType "help", "copyright", "credits" or "license" for more information.>>> capitalizeFirtChar = lambda s: s[:1].upper() + s[1:]>>> print(capitalizeFirtChar('помните своих Предковъ. Сражайся за Правду и Справедливость!'))Помните своих Предковъ. Сражайся за Правду и Справедливость!>>> print(capitalizeFirtChar('хай живе вільна Україна! Хай живе Любовь поміж нас.'))Хай живе вільна Україна! Хай живе Любовь поміж нас.>>> print(capitalizeFirtChar('faith and Labour make Dreams come true.'))Faith and Labour make Dreams come true.
从最初的问题来看,我们想将字符串s = 'the brown fox'中的每个单词大写。如果字符串是s = 'the brown fox',具有非均匀空格怎么办?
def solve(s):# If you want to maintain the spaces in the string, s = 'the brown fox'# Use s.split(' ') instead of s.split().# s.split() returns ['the', 'brown', 'fox']# while s.split(' ') returns ['the', 'brown', '', '', '', '', '', 'fox']capitalized_word_list = [word.capitalize() for word in s.split(' ')]return ' '.join(capitalized_word_list)
def cap_each(string):list_of_words = string.split(" ")
for word in list_of_words:list_of_words[list_of_words.index(word)] = word.capitalize()
return " ".join(list_of_words)