string.title() 为什么把撇号当作新单词的开始?
>>> myStr="madam. i'm adam! i also tried c,o,m,m,a"
>>> myStr.title()
"Madam. I'M Adam! I Also Tried C,O,M,M,A"
这肯定是不对的。为什么一个撇号会被认为是一个新单词的开始呢?这是个陷阱,还是我对标题这个概念理解错了?
4 个回答
2
标题方法会把字符串中每个单词的第一个字母变成大写,其余字母变成小写。单词是由字母组成的子串,这些字母之间被非字母字符(比如数字或空格)隔开。这可能会导致一些意想不到的结果。例如,字符串"x1x"会被转换成"X1X",而不是"X1x"。
基本上,这个方法是按预期工作的。因为撇号确实是非字母字符,所以你会看到上面提到的“意外行为”。
稍微搜索一下可以发现,其他人也觉得这不是最好的做法,因此有一些替代的实现方法被写出来了。可以参考:http://muffinresearch.co.uk/archives/2008/05/27/titlecasepy-titlecase-in-python/
3
你可以使用:
string.capwords()
# 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()
这个方法会返回一个字典,里面包含了本地的习惯用法。
title()
这个方法会返回一个标题格式的字符串:每个单词的首字母大写,其余的字母都是小写。对于8位字符串,这个方法会受到地区设置的影响。
5
这个实现的原理是查看前一个字符,如果前一个字符是字母或数字,就把当前字符变成小写;如果不是,就把当前字符变成大写。简单来说,就是这个过程比较简单。下面是一个纯Python版本的代码示例:
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)