文章来自《Python cookbook》. 翻译仅仅是为了个人学习,其它商业版权纠纷与此无关!
-- 0.706 [DateTime(2004-09-04T19:45:31Z)] TableOfContents
操纵大小写
Credit: Luther Blissett
问题 Problem
You need to convert a string from uppercase to lowercase, or vice versa.
你需要将一个字符串从大写转换为小写,或者相反.
解决 Solution
That's what the upper and lower methods of string objects are for. Each takes no arguments and returns a copy of the string in which each letter has been changed to upper- or lowercase, respectively.
那就是string的方法'upper'和'lower'的用处.它们不需要参数,返回一个原字符串的拷贝--其中的每个字符都被转化为相应的大写或小写.
s.capitalize is similar to s[:1].upper()+s[1:].lower( ). The first character is changed to uppercase, and all others are changed to lowercase. s.title is similar, but it uppercases the first letter of each word:
s.capitalize 类似于s[:1].upper()+s[1:].lower( ).第一个字符被转化为大写,所有其余字符被转化为小写.s.title也类似,不过它将每一个单词的第一个字符转化为大写:
>>> print 'one two three'.capitalize( ) One two three >>> print 'one two three'.title( ) One Two Three
讨论 Discussion
Case manipulation of strings is a very frequent need. Because of this, several string methods let you produce case-altered copies of strings. Moreover, you can also check if a string object is already in a given case form with the methods isupper, islower, and istitle, which all return 1 if the string is nonempty and already meets the uppercase, lowercase, or titlecase constraints. There is no iscapitalized method, but we can code it as a function:
This may not be exactly what you want, because each of the is methods returns 0 for an empty string, and the three case-checking ones also return 0 for strings that, while not empty, contain no letters at all. This iscapitalized function does not quite match these semantics; rather, it accepts a string s only if s starts with an uppercase letter, followed by at least one more character, including at least one more letter somewhere, and all letters except the first one are lowercase. Here's an alternative whose semantics may be easier to understand:
However, this version deviates from the boundary-case semantics of the methods by accepting strings that are empty or contain no letters. Depending on your exact needs for boundary cases, you may of course implement precisely those checks you want to perform.
参考 See Also
The Library Reference section on string methods; Perl Cookbook Recipe 1.9.
