提问人:TIMEX 提问时间:10/11/2009 最后编辑:Peter MortensenTIMEX 更新时间:2/27/2023 访问量:901482
如何将字符串中每个单词的首字母大写?
How can I capitalize the first letter of each word in a string?
问:
s = 'the brown fox'
...在这里做点什么...
s
应为:
'The Brown Fox'
最简单的方法是什么?
答:
字符串的 .title(
) 方法(ASCII 或 Unicode 都可以)这样做:
>>> "hello world".title()
'Hello World'
>>> u"hello world".title()
u'Hello World'
但是,请注意带有嵌入式撇号的字符串,如文档中所述。
该算法使用与语言无关的简单定义,将单词定义为连续字母组。该定义在许多情况下都有效,但这意味着缩略语和所有格中的撇号形成单词边界,这可能不是预期的结果:
>>> "they're bill's friends from the UK".title() "They'Re Bill'S Friends From The Uk"
评论
" ".join(w.capitalize() for w in s.split())
"e g 3b"
"E G 3b"
"e g 3b".title()
"E G 3B"
In [2]: 'tEst'.title() Out[2]: 'Test'
仅仅因为这种事情对我来说很有趣,这里还有两个解决方案。
拆分为单词,对拆分组中的每个单词进行首字母大写,然后重新加入。这将更改将单词分隔为单个空白的空白,无论它是什么。
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())
使用正则表达式匹配字符串的开头或分隔单词的空格,加上单个非空格字符;使用括号标记“匹配组”。编写一个函数,该函数采用匹配对象,并返回未更改的空格匹配组和大写的非空格字符匹配组。然后用于替换模式。这个没有第一个解决方案的标点符号问题,也没有像我的第一个解决方案那样重做空白。这个产生最好的结果。re.sub()
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()
评论
string.capwords
如果 str.title() 不适合您,请自行进行大写。
- 将字符串拆分为单词列表
- 将每个单词的第一个字母大写
- 将单词联接到一个字符串中
单行:
>>> ' '.join([s[0].upper() + s[1:] for s in "they're bill's friends from the UK".split(' ')])
"They're Bill's Friends From The UK"
明确示例:
input = "they're bill's friends from the UK"
words = input.split(' ')
capitalized_words = []
for word in words:
title_case_word = word[0].upper() + word[1:]
capitalized_words.append(title_case_word)
output = ' '.join(capitalized_words)
评论
@jibberia anwser 的复制粘贴就绪版本:
def capitalize(line):
return ' '.join(s[:1].upper() + s[1:] for s in line.split(' '))
评论
str.join
join
str.join
join
str.join
.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 将用于拆分和连接单词。
评论
"There once was a string with an 'that had words right after it and then closed'"
that
"There Once Was A String With An 'that Had Words Right After It And Then Closed'"
title()
title()
capwords()
我真的很喜欢这个答案:
@jibberia anwser 的复制粘贴就绪版本:
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])
评论
要将单词大写...
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))
评论
正如 Mark 所指出的,你应该使用 .title():
"MyAwesomeString".title()
但是,如果想在 Django 模板中将第一个字母大写,你可以使用这个:
{{ "MyAwesomeString"|title }}
或者使用变量:
{{ myvar|title }}
当解决方案简单且安全时,为什么您会使用联接和 for 循环使您的生活复杂化??
只需这样做:
string = "the brown fox"
string[0].upper()+string[1:]
评论
"the brown fox".capitalize()
'this is John'
'This is john'
string.capitalize()
建议的方法 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'
评论
string = "a b 3c"
'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 desired def 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 space from itertools import chain def cap_sentence(s): return ''.join( (c.upper() if prev == ' ' else c) for c, prev in zip(s, chain(' ', s)) )
使用正则表达式,来自 steveha 的回答:
# match the beginning of the string or a space, followed by a non-space import re def cap_sentence(s): return re.sub("(^|\s)(\S)", lambda m: m.group(1) + m.group(2).upper(), s)
现在,这些是发布的其他一些答案,以及如果我们将一个单词定义为句子的开头或空格后面的任何内容,它们将无法按预期工作的输入:
.title()
return s.title() # Undesired outputs: "foO baR" => "Foo Bar" "foo's bar" => "Foo'S Bar" "foo's1bar" => "Foo'S1Bar" "foo 1bar" => "Foo 1Bar"
.capitalize()
或.capwords()
return ' '.join(w.capitalize() for w in s.split()) # or import string return string.capwords(s) # Undesired outputs: "foO baR" => "Foo Bar" "foo bar" => "Foo Bar"
用于拆分将修复第二个输出,但不会修复第一个输出
' '
return ' '.join(w.capitalize() for w in s.split(' ')) # or import string return string.capwords(s, ' ') # Undesired outputs: "foO baR" => "Foo Bar"
.upper()
小心使用多个空格,这可以通过用于拆分来修复(如答案顶部所示)
' '
return ' '.join(w[0].upper() + w[1:] for w in s.split()) # Undesired outputs: "foo bar" => "Foo Bar"
评论
lower 123 upper
lower 123 Upper
upper
"([0-9]+)(\s+.)"
"(^|\s)(\S)"
"([0-9]+)(\s*.)"
WW1 - the great war
WW1 - The Great War
Ww1 ...
WW1
WW1
如果访问 [1:],空字符串将引发错误。因此,我会使用:
def my_uppercase(title):
if not title:
return ''
return title[0].upper() + title[1:]
仅将第一个字母大写。
评论
str.capitalize
return title[:1].upper() + title[1:]
也会解决这个问题,因为像这样切开空字符串会得到 2 个空字符串,连接在一起形成一个返回的空字符串
不要忽视留白。如果你想处理,你得到而不是,你已经破坏了你的空白。上述某些解决方案将丢失空格。这是一个适用于 Python 2 和 3 并保留空白的解决方案。'fred flinstone'
'Fred Flinstone'
'Fred Flinstone'
def propercase(s):
return ''.join(map(''.capitalize, re.split(r'(\s+)', s)))
如果你只想要第一个字母:
>>> 'hello world'.capitalize()
'Hello world'
但要将每个单词大写:
>>> 'hello world'.title()
'Hello World'
评论
'hello New York'.capitalize()
'Hello new york'
如果您想缩小尺寸
# 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
尽管所有答案都已经令人满意,但我会尝试涵盖两个额外的案例以及之前的所有案例。
如果空间不均匀,并且您想保持相同
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
评论
一个适用于 Python 3 的快速函数
Python 3.6.9 (default, Nov 7 2019, 10:44:02)
[GCC 8.3.0] on linux
Type "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.
评论
使用非均匀空格将字符串大写
我想补充一下古普塔@Amit非均匀空间的观点:
从最初的问题开始,我们想将字符串中的每个单词大写。如果字符串具有不均匀的空格怎么办?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)
评论
您的问题最简单的解决方案,它适用于我的情况:
import string
def solve(s):
return string.capwords(s,' ')
s=input()
res=solve(s)
print(res)
.title() 方法不适用于所有测试用例,因此同时使用 .capitalize()、.replace() 和 .split() 是将每个单词的第一个字母大写的最佳选择。
例如:def caps(y):
k=y.split()
for i in k:
y=y.replace(i,i.capitalize())
return y
你可以试试这个。简单而整洁。
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)
另一个单行解决方案可能是:
" ".join(map(lambda d: d.capitalize(), word.split(' ')))
评论
space character
您可以在 Python 中使用 method 将字符串中的每个单词大写:title()
string = "this is a test string"
capitalized_string = string.title()
print(capitalized_string)
输出:
This Is A Test String
如果您将使用 .title() 方法,那么 ' 后面的字母也将变为大写。喜欢这个:
>>> "hello world's".title()
"Hello World'S"
为避免这种情况,请使用字符串库中的 capwords 函数。 喜欢这个:
>>> import string
>>> string.capwords("hello world's")
"Hello World's"
评论