Question 5.17: Converting a String to Upper- or Lowercase You want to conve......

Converting a String to Upper- or Lowercase

You want to convert all the characters in a string to upper- or lowercase letters.

Step-by-Step
The 'Blue Check Mark' means that this solution was answered by an expert.
Learn more on how do we answer questions.

Use the upper or lower function as appropriate.

For example, to convert aBcDe to uppercase, you would use:

>>> “aBcDe”.upper()
‘ABCDE’
>>>

To convert it to lowercase, you would use:

>>> “aBcDe”.lower()
‘abcde’
>>>

Discussion

In common with most functions that manipulate a string in some way, upper and lower do not actually modify the string, but rather return a modified copy of the string.

For example, the following code returns a copy of the string s, but note how the original string is unchanged.

>>> s = “aBcDe”
>>> s.upper()
‘ABCDE’
>>> s
‘aBcDe’
>>>

If you want to change the value of s to be all uppercase, then you need to do the following:

>>> s = “aBcDe”
>>> s = s.upper()
>>> s
‘ABCDE’
>>>

See Also

See Recipe 5.16 for replacing text within strings.

Related Answered Questions

Question: 5.24

Verified Answer:

Create a function that groups together lines of co...
Question: 5.23

Verified Answer:

Use the Python break statement to exit either a wh...
Question: 5.22

Verified Answer:

Use the Python while statement. The while statemen...
Question: 5.21

Verified Answer:

Use the Python for command and iterate over a rang...
Question: 5.20

Verified Answer:

Use one of the logical operators: and, or, and not...
Question: 5.19

Verified Answer:

Use one of the comparison operators: <, >, &...
Question: 5.18

Verified Answer:

Use the Python if command. The following example w...
Question: 5.15

Verified Answer:

Use the Python [:] notation. For example, to cut o...
Question: 5.14

Verified Answer:

Use the find Python function. For example, to find...