-- 0.706 [2004-09-04 19:45:31]

# 操纵大小写

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.

```   1 big = little.upper(  )
2 little = big.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:

```   1 def iscapitalized(s):
2     return s[:1].isupper() and s[1:].islower(  )
```

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:

```   1 def iscapitalized(s):
2     return s == s.capitalize(  )
```

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.

The Library Reference section on string methods; Perl Cookbook Recipe 1.9.

PyCkBk-3-9 (last edited 2009-12-25 07:18:31 by localhost)

• Page.execute = 0.043s
• getACL = 0.011s
• init = 0.000s