Skip to content

Computer Science · Ch 8 — Strings

String Methods and Built-in Functions

8.5

String Methods and Built-in Functions

Python ships with a rich set of built-in functions and methods for working with strings, so most everyday manipulations need no hand-written loop at all. One of them — len() — is a standalone function called as len(s); the rest are methods, called with dot notation on the string itself, e.g. s.upper(). Because strings are immutable, every one of these returns a new value and leaves the original string unchanged.

The commonly used ones follow, each with its behaviour and an example.

len() — length of the string

Returns the number of characters in the given string (spaces and symbols count).

>>> s = 'Hello World!'
>>> len(s)
12

title() — Title Case

Returns the string with the first letter of every word in uppercase and all remaining letters in lowercase.

>>> s = 'india WON the MATCH'
>>> s.title()
'India Won The Match'

lower() — all lowercase

Returns the string with every uppercase letter converted to lowercase.

>>> s = 'india WON the MATCH'
>>> s.lower()
'india won the match'

upper() — all uppercase

Returns the string with every lowercase letter converted to uppercase.

>>> s = 'india WON the MATCH'
>>> s.upper()
'INDIA WON THE MATCH'

count(str, start, end) — how many occurrences

Returns the number of times the substring occurs in the given string. Optional start and end indices restrict the search to that range; if they are omitted, searching runs from index 0 to the length of the string.

>>> s = 'the cat and the dog and the cow'
>>> s.count('the')          # whole string searched
3
>>> s.count('the', 10, 31)  # only within indices 10..30
2

find(str, start, end) — index of first occurrence

Returns the index of the first occurrence of the substring in the given string; the optional start and end limit the search range exactly as in count(). If the substring is not present, it returns -1 (no error).

>>> s = 'the cat and the dog and the cow'
>>> s.find('the')           # first match is at the very start
0
>>> s.find('the', 5, 20)    # first match within indices 5..19
12
>>> s.find('thee')          # absent -> -1
-1

index(str, start, end) — like find(), but raises an error

Same as find(), except that when the substring is not present it raises an exception instead of returning -1.

>>> s = 'the cat and the dog'
>>> s.index('the')
0
>>> s.index('thee')
ValueError: substring not found

endswith() — does it end with...?

Returns True if the string ends with the supplied substring, otherwise False.

>>> s = 'Hello World!'
>>> s.endswith('World!')
True
>>> s.endswith('!')
True
>>> s.endswith('rld')
False

startswith() — does it start with...?

Returns True if the string starts with the supplied substring, otherwise False.

>>> s = 'Hello World!'
>>> s.startswith('He')
True
>>> s.startswith('Hee')
False

The is...() family — testing what a string contains

These methods classify the string's contents and return a Boolean.

isalnum() — True if every character is a letter or a digit (alphanumeric). Whitespace or special symbols anywhere — or an empty string — give False.

>>> 'Result2026'.isalnum()
True
>>> 'Result 2026'.isalnum()    # contains a space
False
>>> 'Result!!'.isalnum()       # contains symbols
False

islower() — True if the string is non-empty and all its alphabets are lowercase, or it has at least one lowercase alphabet and the rest are non-alphabet characters. A string with no alphabet at all gives False.

>>> 'good morning!'.islower()
True
>>> 'good 1234'.islower()
True
>>> 'good ??'.islower()
True
>>> '1234'.islower()           # no alphabet at all
False
>>> 'Good Morning'.islower()   # has uppercase letters
False

isupper() — the mirror image: True if the string is non-empty and all its alphabets are uppercase, or it has at least one uppercase alphabet and the rest are non-alphabet characters.

>>> 'GOOD MORNING!'.isupper()
True
>>> 'GOOD 1234'.isupper()
True
>>> 'GOOD ??'.isupper()
True
>>> '1234'.isupper()
False
>>> 'Good Morning'.isupper()
False

isspace() — True if the string is non-empty and every character is whitespace (blank space, tab, newline or carriage return).

>>> '  \n \t \r'.isspace()
True
>>> 'hi \n'.isspace()          # contains non-space characters
False

istitle() — True if the string is non-empty and in title case, i.e., the first letter of every word is uppercase and the rest lowercase.

>>> 'Hello World!'.istitle()
True
>>> 'hello World!'.istitle()
False

lstrip(), rstrip(), strip() — trimming spaces

  • lstrip() returns the string with spaces removed only on the left.
  • rstrip() returns the string with spaces removed only on the right.
  • strip() returns the string with spaces removed on both the left and the right.
>>> s = '   Hello World!   '
>>> s.lstrip()
'Hello World!   '
>>> s.rstrip()
'   Hello World!'
>>> s.strip()
'Hello World!'

replace(oldstr, newstr) — substitute a substring

Returns a string in which every occurrence of the old substring has been replaced by the new one.

>>> s = 'Hello World!'
>>> s.replace('o', '*')            # every 'o' replaced
'Hell* W*rld!'
>>> s.replace('World', 'Python')   # a whole word replaced
'Hello Python!'
>>> 'Hi World! Hi'.replace('Hi', 'Bye')
'Bye World! Bye'

join() — insert a separator between characters

Called on the separator string, join() returns a string in which the characters of the argument have been joined together with that separator placed between them.

>>> s = 'PYTHON'
>>> sep = '-'          # the separator
>>> sep.join(s)
'P-Y-T-H-O-N'

partition() — split into exactly three parts …

Table 8.2Built-in functions for string manipulations
MethodDescriptionExample
len()Returns the length of the given string>>> str1 = 'Hello World!'
>>> len(str1)
12
title()Returns the string with first letter of every word in the string in uppercase and rest in lowercase>>> str1 = 'hello WORLD!'
>>> str1.title()
'Hello World!'
lower()Returns the string with all uppercase letters converted to lowercase>>> str1 = 'hello WORLD!'
>>> str1.lower()
'hello world!'
upper()Returns the string with all lowercase letters converted to uppercase>>> str1 = 'hello WORLD!'
>>> str1.upper()
'HELLO WORLD!'
count(str, start, end)Returns number of times substring str occurs in the given string. If we do not give start index and end index then searching starts from index 0 and ends at length of the string>>> str1 = 'Hello World! Hello Hello'
>>> str1.count('Hello',12,25)
2
>>> str1.count('Hello')
3
find(str,start, end)Returns the first occurrence of index of substring str occurring in the given string. If we do not give start and end then searching starts from index 0 and ends at length of the string. If the substring is not present in the given string, then the function returns -1>>> str1 = 'Hello World! Hello Hello'
>>> str1.find('Hello',10,20)
13
>>> str1.find('Hello',15,25)
19
>>> str1.find('Hello')
0
>>> str1.find('Hee')
-1
index(str, start, end)Same as find() but raises an exception if the substring is not present in the given string>>> str1 = 'Hello World! Hello Hello'
>>> str1.index('Hello')
0
>>> str1.index('Hee')
ValueError: substring not found
endswith()Returns True if the given string ends with the supplied substring otherwise returns False>>> str1 = 'Hello World!'
>>> str1.endswith('World!')
True
>>> str1.endswith('!')
True
>>> str1.endswith('lde')
False
startswith()Returns True if the given string starts with the supplied substring otherwise returns False>>> str1 = 'Hello World!'
>>> str1.startswith('He')
True
>>> str1.startswith('Hee')
False
isalnum()Returns True if characters of the given string are either alphabets or numeric. If whitespace or special symbols are part of the given string or the string is empty it returns False>>> str1 = 'HelloWorld'
>>> str1.isalnum()
True
>>> str1 = 'HelloWorld2'
>>> str1.isalnum()
True
>>> str1 = 'HelloWorld!!'
>>> str1.isalnum()
False
islower()Returns True if the string is non-empty and has all lowercase alphabets, or has at least one character as lowercase alphabet and rest are non-alphabet characters>>> str1 = 'hello world!'
>>> str1.islower()
True
>>> str1 = 'hello 1234'
>>> str1.islower()
True
>>> str1 = 'hello ??'
>>> str1.islower()
True
>>> str1 = '1234'
>>> str1.islower()
False
>>> str1 = 'Hello World!'
>>> str1.islower()
False
isupper()Returns True if the string is non-empty and has all uppercase alphabets, or has at least one character as uppercase character and rest are non-alphabet characters>>> str1 = 'HELLO WORLD!'
>>> str1.isupper()
True
>>> str1 = 'HELLO 1234'
>>> str1.isupper()
True
>>> str1 = 'HELLO ??'
>>> str1.isupper()
True
>>> str1 = '1234'
>>> str1.isupper()
False
>>> str1 = 'Hello World!'
>>> str1.isupper()
False
isspace()Returns True if the string is non-empty and all characters are white spaces (blank, tab, newline, carriage return)>>> str1 = ' \n \t \r'
>>> str1.isspace()
True
>>> str1 = 'Hello \n'
>>> str1.isspace()
False
istitle()Returns True if the string is non-empty and title case, i.e., the first letter of every word in the string in uppercase and rest in lowercase>>> str1 = 'Hello World!'
>>> str1.istitle()
True
>>> str1 = 'hello World!'
>>> str1.istitle()
False
lstrip()Returns the string after removing the spaces only on the left of the string>>> str1 = ' Hello World! '
>>> str1.lstrip()
'Hello World! '
rstrip()Returns the string after removing the spaces only on the right of the string>>> str1 = ' Hello World!'
>>> str1.rstrip()
' Hello World!'
strip()Returns the string after removing the spaces both on the left and the right of the string>>> str1 = ' Hello World!'
>>> str1.strip()
'Hello World!'
replace(oldstr, newstr)Replaces all occurrences of old string with the new string>>> str1 = 'Hello World!'
>>> str1.replace('o','')
'Hell
W*rld!'
>>> str1 = 'Hello World!'
>>> str1.replace('World','Country')
'Hello Country!'
>>> str1 = 'Hello World! Hello'
>>> str1.replace('Hello','Bye')
'Bye World! Bye'