Python String Methods
Python has a set of built-in methods that you can use on strings.
Note: All string methods returns new values. They do not change the original string.
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the position of where
it was found
format() Formats specified values in a string
format_map( Formats specified values in a string
)
index() Searches the string for a specified value and returns the position of where
it was found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isascii() Returns True if all characters in the string are ascii characters
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Converts the elements of an iterable into a string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of
where it was found
rindex() Searches the string for a specified value and returns the last position of
where it was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning
Python String capitalize() Method
Upper case the first letter in this sentence:
txt = "hello, and welcome to my world."
x = [Link]()
print (x)
Output:
Hello, and welcome to my world.
Definition and Usage
The capitalize() method returns a string where the first character is upper case, and the rest is
lower case.
Syntax
[Link]()
Parameter Values
No parameters
More Examples
Example
The first character is converted to upper case, and the rest are converted to lower case:
txt = "python is FUN!"
x = [Link]()
print (x)
Output:
Python is fun!
Example
See what happens if the first character is a number:
txt = "36 is my age."
x = [Link]()
print (x)
Output:
36 is my age
Python String casefold() Method
Make the string lower case:
txt = "Hello, And Welcome To My World!"
x = [Link]()
print(x)
Output:
hello, and welcome to my world!
Definition and Usage
The casefold() method returns a string where all the characters are lower case. This method is
similar to the lower() method, but the casefold() method is stronger, more aggressive,
meaning that it will convert more characters into lower case, and will find more matches
when comparing two strings and both are converted using the casefold() method.
Syntax
[Link]()
Parameter Values
No parameters
Python String center() Method
Print the word "banana", taking up the space of 20 characters, with "banana" in the middle:
txt = "banana"
x = [Link](20)
print(x)
Output:
banana
Definition and Usage
The center() method will center align the string, using a specified character (space is default)
as the fill character.
Syntax
[Link](length, character)
Parameter Values
Parameter Description
length Required. The length of the returned string
character Optional. The character to fill the missing space on each side. Default is
" " (space)
Example
Using the letter "O" as the padding character:
txt = "banana"
x = [Link](20, "O")
print(x)
Output:
OOOOOOObananaOOOOOOO
Python String count() Method
Return the number of times the value "apple" appears in the string:
txt = "I love apples, apple are my favorite fruit"
x = [Link]("apple")
print(x)
Output:
2
Definition and Usage
The count() method returns the number of times a specified value appears in the string.
Syntax
[Link](value, start, end)
Parameter Values
Parameter Description
value Required. A String. The string to value to search for
start Optional. An Integer. The position to start the search. Default is 0
end Optional. An Integer. The position to end the search. Default is the end
of the string
Example
Search from position 10 to 24:
txt = "I love apples, apple are my favorite fruit"
x = [Link]("apple", 10, 24)
print(x)
Output:
1
Python String encode() Method
UTF-8 encode the string:
txt = "My name is Ståle"
x = [Link]()
print(x)
Output:
b'My name is St\xc3\xe5le'
Definition and Usage
The encode() method encodes the string, using the specified encoding. If no encoding is
specified, UTF-8 will be used.
Syntax
[Link](encoding=encoding, errors=errors)
Python String endswith() Method
Check if the string ends with a punctuation sign (.):
txt = "Hello, welcome to my world."
x = [Link](".")
print(x)
Output:
True
Definition and Usage
The endswith() method returns True if the string ends with the specified value, otherwise
False.
Syntax
[Link](value, start, end)
Parameter Values
Parameter Description
value Required. The value to check if the string ends with
start Optional. An Integer specifying at which position to start the search
end Optional. An Integer specifying at which position to end the search
Example
Check if the string ends with the phrase "my world.":
txt = "Hello, welcome to my world."
x = [Link]("my world.")
print(x)
Output:
True
Example
Check if position 5 to 11 ends with the phrase "my world.":
txt = "Hello, welcome to my world."
x = [Link]("my world.", 5, 11)
print(x)
Output:
False
Python String expandtabs() Method
Set the tab size to 2 whitespaces:
txt = "H\te\tl\tl\to"
x = [Link](2)
print(x)
Output:
Hello
Definition and Usage
The expandtabs() method sets the tab size to the specified number of whitespaces.
Syntax
[Link](tabsize)
Parameter Values
Parameter Description
tabsize Optional. A number specifying the tabsize. Default tabsize is 8
Example
See the result using different tab sizes:
txt = "H\te\tl\tl\to"
print(txt)
print([Link]())
print([Link](2))
print([Link](4))
print([Link](10))
Output:
H e l l o
H e l l o
Hello
H e l l o
H e l l o
Python String find() Method
Where in the text is the word "welcome"?:
txt = "Hello, welcome to my world."
x = [Link]("welcome")
print(x)
Output:
7
Definition and Usage
The find() method finds the first occurrence of the specified value.
The find() method returns -1 if the value is not found.
The find() method is almost the same as the index() method, the only difference is that
the index() method raises an exception if the value is not found. (See example below)
Syntax
[Link](value, start, end)
Parameter Values
Parameter Description
value Required. The value to search for
start Optional. Where to start the search. Default is 0
end Optional. Where to end the search. Default is to the end of the string
Example
Where in the text is the first occurrence of the letter "e"?:
txt = "Hello, welcome to my world."
x = [Link]("e")
print(x)
Output:
1
Example
Where in the text is the first occurrence of the letter "e" when you only search between
position 5 and 10?:
txt = "Hello, welcome to my world."
x = [Link]("e", 5, 10)
print(x)
Output:
8
Example
If the value is not found, the find() method returns -1, but the index() method will raise an
exception:
txt = "Hello, welcome to my world."
print([Link]("q"))
print([Link]("q"))
Output:
-1
Traceback (most recent call last):
File "demo_ref_string_find_vs_index.py", line 4 in <module>
print([Link]("q"))
ValueError: substring not found
Python String format() Method
Insert the price inside the placeholder, the price should be in fixed point, two-decimal format:
txt = "For only {price:.2f} dollars!"
print([Link](price = 49))
Output:
For only 49.00 dollars!
Definition and Usage
The format() method formats the specified value(s) and insert them inside the string's
placeholder.
The placeholder is defined using curly brackets: {}. Read more about the placeholders in the
Placeholder section below.
The format() method returns the formatted string.
Syntax
[Link](value1, value2...)
Parameter Values
Parameter Description
value1, Required. One or more values that should be formatted and inserted in
value2... the string.
The values are either a list of values separated by commas, a key=value
list, or a combination of both.
The values can be of any data type.
The Placeholders
The placeholders can be identified using named indexes {price}, numbered indexes {0}, or
even empty placeholders {}.
Example
Using different placeholder values:
txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age = 36)
txt2 = "My name is {0}, I'm {1}".format("John",36)
txt3 = "My name is {}, I'm {}".format("John",36)
Output:
My name is John, I'm 36
My name is John, I'm 36
My name is John, I'm 36
Python String index() Method
Where in the text is the word "welcome"?:
txt = "Hello, welcome to my world."
x = [Link]("welcome")
print(x)
Output:
7
Definition and Usage
The index() method finds the first occurrence of the specified value.
The index() method raises an exception if the value is not found.
The index() method is almost the same as the find() method, the only difference is that
the find() method returns -1 if the value is not found. (See example below)
Syntax
[Link](value, start, end)
Parameter Values
Parameter Description
value Required. The value to search for
start Optional. Where to start the search. Default is 0
end Optional. Where to end the search. Default is to the end of the string
Example
Where in the text is the first occurrence of the letter "e"?:
txt = "Hello, welcome to my world."
x = [Link]("e")
print(x)
Output:
1
Example
Where in the text is the first occurrence of the letter "e" when you only search between
position 5 and 10?:
txt = "Hello, welcome to my world."
x = [Link]("e", 5, 10)
print(x)
Output:
8
Example
If the value is not found, the find() method returns -1, but the index() method will raise an
exception:
txt = "Hello, welcome to my world."
print([Link]("q"))
print([Link]("q"))
Output:
-1
Traceback (most recent call last):
File "demo_ref_string_find_vs_index.py", line 4 in <module>
print([Link]("q"))
ValueError: substring not found
Python String isalnum() Method
Check if all the characters in the text are alphanumeric:
txt = "Company12"
x = [Link]()
print(x)
Output:
True
Definition and Usage
The isalnum() method returns True if all the characters are alphanumeric, meaning alphabet
letter (a-z) and numbers (0-9).
Example of characters that are not alphanumeric: (space)!#%&? etc.
Syntax
[Link]()
Parameter Values
No parameters.
Example
Check if all the characters in the text is alphanumeric:
txt = "Company 12"
x = [Link]()
print(x)
Output:
False
Python String isalpha() Method
Check if all the characters in the text are letters:
txt = "CompanyX"
x = [Link]()
print(x)
Output:
True
Definition and Usage
The isalpha() method returns True if all the characters are alphabet letters (a-z).
Example of characters that are not alphabet letters: (space)!#%&? etc.
Syntax
[Link]()
Parameter Values
No parameters.
Example
Check if all the characters in the text is alphabetic:
txt = "Company10"
x = [Link]()
print(x)
Output:
False
Python String isascii() Method
Check if all the characters in the text are ascii characters:
txt = "Company123"
x = [Link]()
print(x)
Output:
True
Definition and Usage
The isascii() method returns True if all the characters are ascii characters (a-z).
Syntax
[Link]()
Parameter Values
No parameters.
Python String isdecimal() Method
Check if all the characters in a string are decimals (0-9):
txt = "1234"
x = [Link]()
print(x)
Output:
True
Definition and Usage
The isdecimal() method returns True if all the characters are decimals (0-9).
This method can also be used on unicode objects. See example below.
Syntax
[Link]()
Parameter Values
No parameters.
Python String isdigit() Method
Check if all the characters in the text are digits:
txt = "50800"
x = [Link]()
print(x)
Output:
True
Definition and Usage
The isdigit() method returns True if all the characters are digits, otherwise False.
Exponents, like ², are also considered to be a digit.
Syntax
[Link]()
Parameter Values
No parameters.
Python String isidentifier() Method
Check if the string is a valid identifier:
txt = "Demo"
x = [Link]()
print(x)
Output:
True
Definition and Usage
The isidentifier() method returns True if the string is a valid identifier, otherwise False.
A string is considered a valid identifier if it only contains alphanumeric letters (a-z) and (0-9),
or underscores (_). A valid identifier cannot start with a number, or contain any spaces.
Syntax
[Link]()
Parameter Values
No parameters.
Example
Check if the strings are valid identifiers:
a = "MyFolder"
b = "Demo002"
c = "2bring"
d = "my demo"
print([Link]())
print([Link]())
print([Link]())
print([Link]())
Output:
True
True
False
False
Python String islower() Method
Check if all the characters in the text are in lower case:
txt = "hello world!"
x = [Link]()
print(x)
Output:
True
Definition and Usage
The islower() method returns True if all the characters are in lower case, otherwise False.
Numbers, symbols and spaces are not checked, only alphabet characters.
Syntax
[Link]()
Parameter Values
No parameters.
Example
Check if all the characters in the texts are in lower case:
a = "Hello world!"
b = "hello 123"
c = "mynameisPeter"
print([Link]())
print([Link]())
print([Link]())
Output:
False
True
False
Python String isnumeric() Method
Check if all the characters in the text are numeric:
txt = "565543"
x = [Link]()
print(x)
Output:
True
Definition and Usage
The isnumeric() method returns True if all the characters are numeric (0-9), otherwise False.
Exponents, like ² and ¾ are also considered to be numeric values.
"-1" and "1.5" are NOT considered numeric values, because all the characters in the string
must be numeric, and the - and the . are not.
Syntax
[Link]()
Parameter Values
No parameters.
Python String isprintable() Method
Check if all the characters in the text are printable:
txt = "Hello! Are you #1?"
x = [Link]()
print(x)
Output:
True
Definition and Usage
The isprintable() method returns True if all the characters are printable, otherwise False.
Example of none printable character can be carriage return and line feed.
Syntax
[Link]()
Parameter Values
No parameters.
Example
Check if all the characters in the text are printable:
txt = "Hello!\nAre you #1?"
x = [Link]()
print(x)
Output:
False
Python String isspace() Method
Check if all the characters in the text are whitespaces:
txt = " "
x = [Link]()
print(x)
Output:
True
Definition and Usage
The isspace() method returns True if all the characters in a string are whitespaces, otherwise
False.
Syntax
[Link]()
Parameter Values
No parameters.
Example
Check if all the characters in the text are whitespaces:
txt = " s "
x = [Link]()
print(x)
Output:
False
Python String istitle() Method
Check if each word start with an upper case letter:
txt = "Hello, And Welcome To My World!"
x = [Link]()
print(x)
Output:
True
Definition and Usage
The istitle() method returns True if all words in a text start with a upper case letter, AND the
rest of the word are lower case letters, otherwise False.
Symbols and numbers are ignored.
Syntax
[Link]()
Parameter Values
No parameters.
Example
Check if each word start with an upper case letter:
a = "HELLO, AND WELCOME TO MY WORLD"
b = "Hello"
c = "22 Names"
d = "This Is %'!?"
print([Link]())
print([Link]())
print([Link]())
print([Link]())
Output:
False
True
True
True
Python String isupper() Method
Check if all the characters in the text are in upper case:
txt = "THIS IS NOW!"
x = [Link]()
print(x)
Output:
True
Definition and Usage
The isupper() method returns True if all the characters are in upper case, otherwise False.
Numbers, symbols and spaces are not checked, only alphabet characters.
Syntax
[Link]()
Parameter Values
No parameters.
Example
Check if all the characters in the texts are in upper case:
a = "Hello World!"
b = "hello 123"
c = "MY NAME IS PETER"
print([Link]())
print([Link]())
print([Link]())
Output:
False
False
True
Python String join() Method
Join all items in a tuple into a string, using a hash character as separator:
myTuple = ("John", "Peter", "Vicky")
x = "#".join(myTuple)
print(x)
Output:
JohnPeterVicky
Definition and Usage
The join() method takes all items in an iterable and joins them into one string.
A string must be specified as the separator.
Syntax
[Link](iterable)
Parameter Values
Parameter Description
iterable Required. Any iterable object where all the returned values are strings
Example
Join all items in a dictionary into a string, using the word "TEST" as separator:
myDict = {"name": "John", "country": "Norway"}
mySeparator = "TEST"
x = [Link](myDict)
print(x)
Output:
nameTESTcountry
Python String ljust() Method
Return a 20 characters long, left justified version of the word "banana":
txt = "banana"
x = [Link](20)
print(x, "is my favorite fruit.")
Output:
banana is my favorite fruit.
Note: In the result, there are actually 14 whitespaces to the right of the word banana.
Definition and Usage
The ljust() method will left align the string, using a specified character (space is default) as
the fill character.
Syntax
[Link](length, character)
Parameter Values
Parameter Description
length Required. The length of the returned string
character Optional. A character to fill the missing space (to the right of the string).
Default is " " (space).
Example
Using the letter "A" as the padding character:
txt = "banana"
x = [Link](20, "A")
print(x)
Output:
bananaAAAAAAAAAAAAAA
Python String lower() Method
Lower case the string:
txt = "Hello my FRIENDS"
x = [Link]()
print(x)
Output:
hello my friends
Definition and Usage
The lower() method returns a string where all characters are lower case.
Symbols and Numbers are ignored.
Syntax
[Link]()
Parameter Values
No parameters
Python String lstrip() Method
Remove spaces to the left of the string:
txt = " banana "
x = [Link]()
print("of all fruits", x, "is my favorite")
Output:
of all fruits banana is my favorite
Definition and Usage
The lstrip() method removes any leading characters (space is the default leading character to
remove)
Syntax
[Link](characters)
Parameter Values
Parameter Description
characters Optional. A set of characters to remove as leading characters
Example
Remove the leading characters:
txt = ",,,,,ssaaww.....banana"
x = [Link](",.asw")
print(x)
Output:
banana
Python String maketrans() Method
Create a mapping table, and use it in the translate() method to replace any "S" characters with
a "P" character:
txt = "Hello Sam!"
mytable = [Link]("S", "P")
print([Link](mytable))
Output:
Hello Pam!
Python String partition() Method
Search for the word "bananas", and return a tuple with three elements:
1 - everything before the "match"
2 - the "match"
3 - everything after the "match"
txt = "I could eat bananas all day"
x = [Link]("bananas")
print(x)
Output:
('I could eat ', 'bananas', ' all day')
Definition and Usage
The partition() method searches for a specified string, and splits the string into a tuple
containing three elements.
The first element contains the part before the specified string.
The second element contains the specified string.
The third element contains the part after the string.
Note: This method searches for the first occurrence of the specified string.
Syntax
[Link](value)
Parameter Values
Parameter Description
value Required. The string to search for
Example
If the specified value is not found, the partition() method returns a tuple containing: 1 - the
whole string, 2 - an empty string, 3 - an empty string:
txt = "I could eat bananas all day"
x = [Link]("apples")
print(x)
Output:
('I could eat bananas all day', '', '')
Python String replace() Method
Replace the word "bananas":
txt = "I like bananas"
x = [Link]("bananas", "apples")
print(x)
Output:
I like apples
Definition and Usage
The replace() method replaces a specified phrase with another specified phrase.
Note: All occurrences of the specified phrase will be replaced, if nothing else is specified.
Syntax
[Link](oldvalue, newvalue, count)
Parameter Values
Parameter Description
oldvalue Required. The string to search for
newvalue Required. The string to replace the old value with
count Optional. A number specifying how many occurrences of the old value
you want to replace. Default is all occurrences
Example
Replace all occurrence of the word "one":
txt = "one one was a race horse, two two was one too."
x = [Link]("one", "three")
print(x)
Output:
three three was a race horse, two two was three too."
Python String rfind() Method
Where in the text is the last occurrence of the string "casa"?:
txt = "Mi casa, su casa."
x = [Link]("casa")
print(x)
Output:
12
Python RegEx / Regular Expression
A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern.
RegEx can be used to check if a string contains the specified search pattern.
RegEx Module
Python has a built-in package called re, which can be used to work with Regular Expressions.
Import the re module:
import re
RegEx in Python
When you have imported the re module, you can start using regular expressions:
Search the string to see if it starts with "The" and ends with "Spain":
import re
txt = "The rain in Spain"
x = [Link]("^The.*Spain$", txt)
Output:
YES! We have a match!
RegEx Functions
The re module offers a set of functions that allows us to search a string for a match:
Functio Description
n
findall Returns a list containing all matches
search Returns a Match object if there is a match anywhere in the string
split Returns a list where the string has been split at each match
sub Replaces one or many matches with a string
Metacharacters are characters with a special meaning:
Characte Description Example
r
[] A set of characters "[a-m]"
\ Signals a special sequence (can also be used to escape "\d"
special characters)
. Any character (except newline character) "he..o"
^ Starts with "^hello"
$ Ends with "planet$"
* Zero or more occurrences "he.*o"
+ One or more occurrences "he.+o"
? Zero or one occurrences "he.?o"
{} Exactly the specified number of occurrences "he.{2}o"
| Either or "falls|stays"
() Capture and group
Special Sequences
A special sequence is a \ followed by one of the characters in the list below, and has a special
meaning:
Characte Description Example
r
\A Returns a match if the specified characters are at the "\AThe"
beginning of the string
\b Returns a match where the specified characters are at the r"\bain"
beginning or at the end of a word
(the "r" in the beginning is making sure that the string is r"ain\b"
being treated as a "raw string")
\B Returns a match where the specified characters are present, r"\Bain"
but NOT at the beginning (or at the end) of a word
(the "r" in the beginning is making sure that the string is r"ain\B"
being treated as a "raw string")
\d Returns a match where the string contains digits (numbers "\d"
from 0-9)
\D Returns a match where the string DOES NOT contain digits "\D"
\s Returns a match where the string contains a white space "\s"
character
\S Returns a match where the string DOES NOT contain a "\S"
white space character
\w Returns a match where the string contains any word "\w"
characters (characters from a to Z, digits from 0-9, and the
underscore _ character)
\W Returns a match where the string DOES NOT contain any "\W"
word characters
\Z Returns a match if the specified characters are at the end of "Spain\Z"
the string
Sets
A set is a set of characters inside a pair of square brackets [] with a special meaning:
Set Description
[arn] Returns a match where one of the specified characters (a, r, or n) is present
[a-n] Returns a match for any lower case character, alphabetically between a and n
[^arn] Returns a match for any character EXCEPT a, r, and n
[0123] Returns a match where any of the specified digits (0, 1, 2, or 3) are present
[0-9] Returns a match for any digit between 0 and 9
[0-5][0- Returns a match for any two-digit numbers from 00 and 59
9]
[a-zA- Returns a match for any character alphabetically between a and z, lower case
Z] OR upper case
[+] In sets, +, *, ., |, (), $,{} has no special meaning, so [+] means: return a match
for any + character in the string
The findall() Function
The findall() function returns a list containing all matches.
Example
Print a list of all matches:
import re
txt = "The rain in Spain"
x = [Link]("ai", txt)
print(x)
Output:
['ai', 'ai']
The list contains the matches in the order they are found.
If no matches are found, an empty list is returned:
Example
Return an empty list if no match was found:
import re
txt = "The rain in Spain"
x = [Link]("Portugal", txt)
print(x)
Output:
[]
No match
The search() Function
The search() function searches the string for a match, and returns a Match object if there is a
match.
If there is more than one match, only the first occurrence of the match will be returned:
Example
Search for the first white-space character in the string:
import re
txt = "The rain in Spain"
x = [Link]("\s", txt)
print("The first white-space character is located in position:", [Link]())
Output:
The first white-space character is located in position: 3
If no matches are found, the value None is returned:
Example
Make a search that returns no match:
import re
txt = "The rain in Spain"
x = [Link]("Portugal", txt)
print(x)
Output:
None
The split() Function
The split() function returns a list where the string has been split at each match:
Example
Split at each white-space character:
import re
txt = "The rain in Spain"
x = [Link]("\s", txt)
print(x)
Output:
['The', 'rain', 'in', 'Spain']
You can control the number of occurrences by specifying the maxsplit parameter:
Example
Split the string only at the first occurrence:
import re
txt = "The rain in Spain"
x = [Link]("\s", txt, 1)
print(x)
Output:
['The', 'rain in Spain']
The sub() Function
The sub() function replaces the matches with the text of your choice:
Example
Replace every white-space character with the number 9:
import re
txt = "The rain in Spain"
x = [Link]("\s", "9", txt)
print(x)
Output:
The9rain9in9Spain
You can control the number of replacements by specifying the count parameter:
Example
Replace the first 2 occurrences:
import re
txt = "The rain in Spain"
x = [Link]("\s", "9", txt, 2)
print(x)
Output:
The9rain9in Spain
Match Object
A Match Object is an object containing information about the search and the result.
Note: If there is no match, the value None will be returned, instead of the Match Object.
Example
Do a search that will return a Match Object:
import re
txt = "The rain in Spain"
x = [Link]("ai", txt)
print(x) #this will print an object
Output:
<_sre.SRE_Match object; span=(5, 7), match='ai'>
The Match object has properties and methods used to retrieve information about the search,
and the result:
.span() returns a tuple containing the start-, and end positions of the match.
.string returns the string passed into the function
.group() returns the part of the string where there was a match
Example
Print the position (start- and end-position) of the first match occurrence.
The regular expression looks for any words that starts with an upper case "S":
import re
txt = "The rain in Spain"
x = [Link](r"\bS\w+", txt)
print([Link]())
Output:
(12, 17)
Example
Print the string passed into the function:
import re
txt = "The rain in Spain"
x = [Link](r"\bS\w+", txt)
print([Link])
Output:
The rain in Spain
Example
Print the part of the string where there was a match.
The regular expression looks for any words that starts with an upper case "S":
import re
txt = "The rain in Spain"
x = [Link](r"\bS\w+", txt)
print([Link]())
Output:
Spain
Metacharacters
Metacharacters are characters with a special meaning:
[] A set of characters "[a-m]"
import re
txt = "The rain in Spain"
#Find all lower case characters alphabetically between "a" and "m":
x = [Link]("[a-m]", txt)
print(x)
Output:
['h', 'e', 'a', 'i', 'i', 'a', 'i']
\ Signals a special sequence (can also be used to escape special characters) "\d"
import re
txt = "That will be 59 dollars"
#Find all digit characters:
x = [Link]("\d", txt)
print(x)
Output:
['5', '9']
. Any character (except newline character) "he..o"
import re
txt = "hello planet"
#Search for a sequence that starts with "he", followed by two (any) characters, and an "o":
x = [Link]("he..o", txt)
print(x)
Output:
['hello']
^ Starts with "^hello"
import re
txt = "hello planet"
#Check if the string starts with 'hello':
x = [Link]("^hello", txt)
if x:
print("Yes, the string starts with 'hello'")
else:
print("No match")
Output:
Yes, the string starts with 'hello'
$ Ends with "planet$"
import re
txt = "hello planet"
#Check if the string ends with 'planet':
x = [Link]("planet$", txt)
if x:
print("Yes, the string ends with 'planet'")
else:
print("No match")
Output:
Yes, the string ends with 'planet'
* Zero or more occurrences "he.*o"
import re
txt = "hello planet"
#Search for a sequence that starts with "he", followed by 0 or more (any) characters, and an
"o":
x = [Link]("he.*o", txt)
print(x)
Output
['hello']
+ One or more occurrences "he.+o"
import re
txt = "hello planet"
#Search for a sequence that starts with "he", followed by 1 or more (any) characters,
and an "o":
x = [Link]("he.+o", txt)
print(x)
output:
['hello']
? Zero or one occurrences "he.?o"
import re
txt = "hello planet"
#Search for a sequence that starts with "he", followed by 0 or 1 (any) character, and an "o":
x = [Link]("he.?o", txt)
print(x)
#This time we got no match, because there were not zero, not one, but two characters
between "he" and the "o"
Output:
[]
{} Exactly the specified number of occurrences "he.{2}o"
import re
txt = "hello planet"
#Search for a sequence that starts with "he", followed excactly 2 (any) characters, and an "o":
x = [Link]("he.{2}o", txt)
print(x)
Output:
['hello']
| Either or "falls|stays"
import re
txt = "The rain in Spain falls mainly in the plain!"
#Check if the string contains either "falls" or "stays":
x = [Link]("falls|stays", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
Output:
['falls']
Yes, there is at least one match!
Special Sequences
A special sequence is a \ followed by one of the characters in the list below, and has a special
meaning:
Characte Description Example
r
\A Returns a match if the specified characters are at the beginning "\AThe"
of the string
import re
txt = "The rain in Spain"
#Check if the string starts with "The":
x = [Link]("\AThe", txt)
print(x)
if x:
print("Yes, there is a match!")
else:
print("No match")
Output:
['The']
Yes, there is a match!
\ Returns a match where the specified characters are at the beginning or at r"\bain"
b the end of a word
(the "r" in the beginning is making sure that the string is being treated as a r"ain\b"
"raw string")
import re
txt = "The rain in Spain"
#Check if "ain" is present at the beginning of a WORD:
x = [Link](r"\bain", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
Output:
[]
No match
import re
txt = "The rain in Spain"
#Check if "ain" is present at the end of a WORD:
x = [Link](r"ain\b", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
Output:
['ain', 'ain']
Yes, there is at least one match!
\ Returns a match where the specified characters are present, but NOT at the r"\
B beginning (or at the end) of a word Bain"
(the "r" in the beginning is making sure that the string is being treated as a
"raw string") r"ain\
B"
import re
txt = "The rain in Spain"
#Check if "ain" is present, but NOT at the beginning of a word:
x = [Link](r"\Bain", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
Output:
['ain', 'ain']
Yes, there is at least one match!
\d Returns a match where the string contains digits (numbers from 0-9) "\d"
import re
txt = "The rain in Spain"
#Check if the string contains any digits (numbers from 0-9):
x = [Link]("\d", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
Output:
[]
No match
\D Returns a match where the string DOES NOT contain digits "\D"
import re
txt = "The rain in Spain"
#Return a match at every no-digit character:
x = [Link]("\D", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
Output:
['T', 'h', 'e', ' ', 'r', 'a', 'i', 'n', ' ', 'i', 'n', ' ', 'S', 'p', 'a', 'i', 'n']
Yes, there is at least one match!
\s Returns a match where the string contains a white space character "\s"
import re
txt = "The rain in Spain"
#Return a match at every white-space character:
x = [Link]("\s", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
Output:
[' ', ' ', ' ']
Yes, there is at least one match!
\S Returns a match where the string DOES NOT contain a white space character "\S"
import re
txt = "The rain in Spain"
#Return a match at every NON white-space character:
x = [Link]("\S", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
Output:
['T', 'h', 'e', 'r', 'a', 'i', 'n', 'i', 'n', 'S', 'p', 'a', 'i', 'n']
Yes, there is at least one match!
\ Returns a match where the string contains any word characters (characters from "\
w a to Z, digits from 0-9, and the underscore _ character) w"
import re
txt = "The rain in Spain"
#Return a match at every word character (characters from a to Z, digits from 0-9, and the
underscore _ character):
x = [Link]("\w", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
Output:
['T', 'h', 'e', 'r', 'a', 'i', 'n', 'i', 'n', 'S', 'p', 'a', 'i', 'n']
Yes, there is at least one match!
\W Returns a match where the string DOES NOT contain any word characters "\W"
import re
txt = "The rain in Spain"
#Return a match at every NON word character (characters NOT between a and Z. Like "!",
"?" white-space etc.):
x = [Link]("\W", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
Output:
[' ', ' ', ' ']
Yes, there is at least one match!
\Z Returns a match if the specified characters are at the end of the string "Spain\Z"
import re
txt = "The rain in Spain"
#Check if the string ends with "Spain":
x = [Link]("Spain\Z", txt)
print(x)
if x:
print("Yes, there is a match!")
else:
print("No match")
Output:
['Spain']
Yes, there is a match!
Sets
A set is a set of characters inside a pair of square brackets [] with a special meaning:
[arn] Returns a match where one of the specified characters (a, r, or n) is present
import re
txt = "The rain in Spain"
#Check if the string has any a, r, or n characters:
x = [Link]("[arn]", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
Output:
['r', 'a', 'n', 'n', 'a', 'n']
Yes, there is at least one match!
[a-n] Returns a match for any lower case character, alphabetically between a and n
import re
txt = "The rain in Spain"
#Check if the string has any characters between a and n:
x = [Link]("[a-n]", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
Output:
['h', 'e', 'a', 'i', 'n', 'i', 'n', 'a', 'i', 'n']
Yes, there is at least one match!
[^arn] Returns a match for any character EXCEPT a, r, and n
import re
txt = "The rain in Spain"
#Check if the string has other characters than a, r, or n:
x = [Link]("[^arn]", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
Output:
['T', 'h', 'e', ' ', 'i', ' ', 'i', ' ', 'S', 'p', 'i']
Yes, there is at least one match!
[0123] Returns a match where any of the specified digits (0, 1, 2, or 3) are present
import re
txt = "The rain in Spain"
#Check if the string has any 0, 1, 2, or 3 digits:
x = [Link]("[0123]", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
Output:
[]
No match
[0-9] Returns a match for any digit between 0 and 9
import re
txt = "8 times before 11:45 AM"
#Check if the string has any digits:
x = [Link]("[0-9]", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
Output:
['8', '1', '1', '4', '5']
Yes, there is at least one match!
[0-5][0-9] Returns a match for any two-digit numbers from 00 and 59
import re
txt = "8 times before 11:45 AM"
#Check if the string has any two-digit numbers, from 00 to 59:
x = [Link]("[0-5][0-9]", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
Output:
['11', '45']
Yes, there is at least one match!
[a-zA-Z] Returns a match for any character alphabetically between a and z, lower case
OR upper case
import re
txt = "8 times before 11:45 AM"
#Check if the string has any characters from a to z lower case, and A to Z upper case:
x = [Link]("[a-zA-Z]", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
Output:
['t', 'i', 'm', 'e', 's', 'b', 'e', 'f', 'o', 'r', 'e', 'A', 'M']
Yes, there is at least one match!
[+ In sets, +, *, ., |, (), $,{} has no special meaning, so [+] means: return a match for
] any + character in the string
import re
txt = "8 times before 11:45 AM"
#Check if the string has any + characters:
x = [Link]("[+]", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
Output:
[]
No match
Pattern matching in Python with Regex
What is Regular Expression?
In the real world, string parsing in most programming languages is handled by regular
expression. Regular expression in a python programming language is a method used for
matching text pattern.
The “re” module which comes with every python installation provides regular expression
support.
In python, a regular expression search is typically written as:
match = [Link](pattern, string)
The [Link]() method takes two arguments, a regular expression pattern and a string and
searches for that pattern within the string. If the pattern is found within the string, search()
returns a match object or None otherwise. So in a regular expression, given a string,
determine whether that string matches a given pattern, and, optionally, collect substrings that
contain relevant information. A regular expression can be used to answer questions like −
Is this string a valid URL?
Which users in /etc/passwd are in a given group?
What is the date and time of all warning messages in a log file?
What username and document were requested by the URL a visitor typed?
Matching patterns
Regular expressions are complicated mini-language. They rely on special characters to match
unknown strings, but let's start with literal characters, such as letters, numbers, and the space
character, which always match them. Let's see a basic example:
#Need module 're' for regular expression
import re
#
search_string ="King of Kings"
pattern = "King"
match = [Link](pattern, search_string)
#If-statement after search() tests if it succeeded
if match:
print("regex matches: ", [Link]())
else:
print('pattern not found')
Output:
regex matches: King