Python online course

Python String Functions

Learn how to inspect, clean, test, and transform Python strings with len(), lower(), upper(), strip(), swapcase(), isdigit(), and islower().

A string is a sequence of characters used to represent text. Python string values can be written with single quotes, double quotes, or other valid literal forms such as triple quotes for multiline text.

greeting = 'Hello world!'
other_greeting = "Hello world!"

multiline = '''This text
uses more than one line.'''

This lesson uses greeting as a working example. Python strings are immutable, which means their contents cannot be changed in place. Most string operations return a new string. They do not automatically replace the original value.

greeting = 'Hello world!'
changed = greeting.lower()

print(greeting)  # Hello world!
print(changed)   # hello world!

To retain a transformed value in the same variable, assign the returned string back to it:

greeting = greeting.lower()

String methods and built-in functions

A string method is an operation called on a string object with dot notation. The method name is followed by parentheses:

greeting.lower()
greeting.strip()

A built-in function is provided by Python and called directly. The len() function receives the string as an argument:

len(greeting)

Do not write greeting.len(). len is a built-in function, not a string method.

Many string methods return another string, such as lower(), upper(), capitalize(), swapcase(), and strip(). Predicate methods such as isdigit() and islower() test a condition and return a Boolean value: True or False.

Measuring length with len()

len(string) returns the total number of characters in a string. Spaces and punctuation count as characters.

greeting = 'Hello world!'
print(len(greeting))

The result is 12: five characters in Hello, one space, five characters in world, and one exclamation mark.

Changing letter case

Case-conversion methods return new strings. Digits, spaces, and punctuation are not affected because they have no uppercase or lowercase form.

lower()

lower() returns a lowercase version of the string.

text = 'Hello WORLD!'
print(text.lower())  # hello world!

upper()

upper() returns an uppercase version of the string.

text = 'Hello world! 42'
print(text.upper())  # HELLO WORLD! 42

capitalize()

capitalize() capitalizes the first character and lowercases applicable remaining cased characters.

text = 'hELLO WORLD!'
print(text.capitalize())  # Hello world!

swapcase()

swapcase() exchanges uppercase letters and lowercase letters. Nonalphabetic characters remain unchanged.

text = 'Hello WORLD! 42'
print(text.swapcase())  # hELLO world! 42

Testing string content and case

Methods ending in is commonly test a property and return a Boolean value. Boolean values are written as True and False and are often used in conditional statements such as if.

isdigit()

isdigit() returns True when a nonempty string consists only of digit characters. Letters, spaces, and punctuation cause the test to return False.

print('42'.isdigit())       # True
print('42 people'.isdigit()) # False
print(' 42'.isdigit())       # False

islower()

islower() returns True when the string contains at least one cased alphabetic character and all of its cased alphabetic characters are lowercase. A mixed-case string returns False because it contains an uppercase letter.

print('hello'.islower())       # True
print('Hello'.islower())       # False
print('hello world!'.islower()) # True
print('123!'.islower())         # False

Ordinary text such as 'Hello world!' returns False from isdigit() because it contains letters rather than only digit characters.

Removing surrounding whitespace with strip()

Whitespace includes characters such as spaces, tabs, and line breaks. strip() removes whitespace from the beginning and end of a string. It does not remove spaces in the middle of the text.

name = '  Ada Lovelace  '
clean_name = name.strip()

print(clean_name)  # Ada Lovelace

The space between Ada and Lovelace remains. If the cleaned value should replace the original, assign it back:

name = name.strip()

Common Python string functions and methods

OperationCall patternPurposeReturn typeExample result
len()len(text)Counts all characters, including spaces and punctuation.int12
capitalize()text.capitalize()Capitalizes the first character and normalizes other cased characters.str'Hello world!'
isdigit()text.isdigit()Checks whether the nonempty string contains only digit characters.boolTrue
islower()text.islower()Checks whether all cased letters are lowercase and at least one exists.boolTrue
lower()text.lower()Creates a lowercase version.str'hello world!'
upper()text.upper()Creates an uppercase version.str'HELLO WORLD!'
strip()text.strip()Removes leading and trailing whitespace.str'Ada Lovelace'
swapcase()text.swapcase()Exchanges uppercase and lowercase letters.str'hELLO wORLD!'

Reading results in the Python interpreter

You can experiment with string functions at the interactive Python prompt. An expression typed at the prompt displays its result immediately.

>>> new_string = 'Hello world!'
>>> new_string
'Hello world!'
>>> len(new_string)
12
>>> new_string.isdigit()
False
>>> new_string.islower()
False
>>> new_string.lower()
'hello world!'
>>> new_string.swapcase()
'hELLO WORLD!'
>>> new_string
'Hello world!'

The final result shows that calling lower() or swapcase() does not change new_string. The returned value must be assigned if you want to keep it.

Practical examples

Cleaning user-entered text

name = '  Ada Lovelace  '
name = name.strip()
print(name)  # Ada Lovelace

This is useful for text collected with input, where a user might accidentally type spaces before or after the intended value. Learn more about collecting values with Python user input.

Validating a numeric-looking entry

age_text = '42'

if age_text.isdigit():
    print('The entry contains only digits.')

An entry such as '42 years' or ' 42 ' does not pass the direct test. If surrounding whitespace is not meaningful, clean it first:

age_text = ' 42 '
age_text = age_text.strip()

if age_text.isdigit():
    print('The entry contains only digits.')

Normalizing text for comparison

answer = 'YES'

if answer.lower() == 'yes':
    print('The answer is yes.')

answer.lower() produces a consistent lowercase value for comparison. The original answer remains 'YES' unless you write answer = answer.lower().

Transformation and test results

Starting stringOperationResultWhat the result demonstrates
'Hello world!'lower()'hello world!'Letters become lowercase; the space and exclamation mark remain.
'Hello world!'swapcase()'hELLO WORLD!'Each cased letter changes to the opposite case.
'42'isdigit()TrueThe string contains only digit characters.
'42 people'isdigit()FalseLetters and spaces prevent a digit-only match.
' Ada Lovelace 'strip()'Ada Lovelace'Only whitespace at the two ends is removed.

Troubleshooting common mistakes

  • Using text.len(): Call the built-in function as len(text).
  • Expecting a method to modify the variable: Assign the returned value, for example text = text.strip() or text = text.lower().
  • Expecting strip() to remove every space: It removes whitespace only at the start and end. Internal spaces remain.
  • Getting False from isdigit(): Check for letters, punctuation, or leading and trailing spaces. Use text.strip().isdigit() when surrounding whitespace should be ignored.
  • Misunderstanding islower(): Mixed-case text returns False. A string with no cased letters, such as digit-only text, also returns False.

Next steps

After learning these basic operations, continue with Python strings, learn how to access individual characters, and practice searching within strings.