The title method capitalizes the first letter of each word in the string (and makes the rest lower case). Words are identified as substrings of alphabetic characters that are separated by non-alphabetic characters, such as digits, or whitespace. This can lead to some unexpected behavior. For example, the string "x1x" will be converted to "X1X" instead of "X1x".
def title(string):
result = []
prev_letter = ' '
for ch in string:
if not prev_letter.isalpha():
result.append(ch.upper())
else:
result.append(ch.lower())
prev_letter = ch
return "".join(result)
# Capitalize the words in a string, e.g. " aBc dEf " -> "Abc Def".
def capwords(s, sep=None):
"""capwords(s, [sep]) -> string
Split the argument into words using split, capitalize each
word using capitalize, and join the capitalized words using
join. Note that this replaces runs of whitespace characters by
a single space.
"""
return (sep or ' ').join(x.capitalize() for x in s.split(sep))
而且,由于title()依赖于区域设置,请检查您的区域设置,看看这是否是有意的:
locale.localeconv()
Returns the database of the local conventions as a
dictionary.
title()
Return a titlecased version of the string: words start with
uppercase characters, all remaining cased characters are lowercase. For 8-bit strings, this method is locale-dependent.
{a1}
基本上,按计划工作。由于撇号实际上是非字母的,因此您会得到上面概述的“意外行为”。在
一点谷歌搜索表明,其他人觉得这并不完全是最好的事情,而且已经编写了替代的实现。请参见:http://muffinresearch.co.uk/archives/2008/05/27/titlecasepy-titlecase-in-python/
因为实现是通过查看前一个字符来工作的,如果是字母数字,则将当前字符小写,否则将大写。也就是说,它相对简单,下面是它的纯python版本的样子:
您可以使用:
string.capwords()
而且,由于
title()
依赖于区域设置,请检查您的区域设置,看看这是否是有意的:相关问题 更多 >
编程相关推荐