Python Strings
In Python, a string is a sequence of characters. For example, "hello" is a string
containing a sequence of characters 'h' , 'e' , 'l' , 'l' , and 'o' .
We use single quotes or double quotes to represent a string in Python. For example,
# create a string using double quotes
string1 = "Python programming"
# create a string using single quotes
string1 = 'Python programming'
Here, we have created a string variable named string1 . The variable is initialized with
the string "Python Programming" .
Example: Python String
# create string type variables
name = "Python"
print(name)
message = "I love Python."
print(message)
Output
Python
I love Python.
In the above example, we have created string-type variables: name and message with
values "Python" and "I love Python" respectively.
Here, we have used double quotes to represent strings, but we can use single quotes
too.
Access String Characters in Python
We can access the characters in a string in three ways.
Indexing: One way is to treat strings as a list and use index values.
For example,
greet = 'hello'
# access 1st index element
print(greet[1]) # "e"
Negative Indexing: Similar to a list, Python allows negative indexing for its
strings. For example,
greet = 'hello'
# access 4th last element
print(greet[-4]) # "e"
Slicing: Access a range of characters in a string by using the slicing operator
colon : . For example,
greet = 'Hello'
# access character from 1st index to 3rd index
print(greet[1:4]) # "ell"
Note: If we try to access an index out of the range or use numbers other than an
integer, we will get errors.
Python Strings are Immutable
In Python, strings are immutable. That means the characters of a string cannot be
changed. For example,
message = 'Hola Amigos'
message[0] = 'H'
print(message)
Output
TypeError: 'str' object does not support item assignment
However, we can assign the variable name to a new string. For example,
message = 'Hola Amigos'
# assign new string to message variable
message = 'Hello Friends'
print(message); # prints "Hello Friends"
Python Multiline String
We can also create a multiline string in Python. For this, we use triple double
quotes """ or triple single quotes ''' . For example,
# multiline string
message = """
Never gonna give you up
Never gonna let you down
"""
print(message)
Output
Never gonna give you up
Never gonna let you down
In the above example, anything inside the enclosing triple quotes is one multiline string.
Python String Operations
Many operations can be performed with strings, which makes it one of the most
used data types in Python.
1. Compare Two Strings
We use the == operator to compare two strings. If two strings are equal, the operator
returns True . Otherwise, it returns False . For example,
str1 = "Hello, world!"
str2 = "I love Swift."
str3 = "Hello, world!"
# compare str1 and str2
print(str1 == str2)
# compare str1 and str3
print(str1 == str3)
Output
False
True
In the above example,
1. str1 and str2 are not equal. Hence, the result is False .
2. str1 and str3 are equal. Hence, the result is True .
2. Join Two or More Strings
In Python, we can join (concatenate) two or more strings using the + operator.
greet = "Hello, "
name = "Jack"
# using + operator
result = greet + name
print(result)
# Output: Hello, Jack
In the above example, we have used the + operator to join two strings: greet and name .
Iterate Through a Python String
We can iterate through a string using a for loop. For example,
greet = 'Hello'
# iterating through greet string
for i in greet:
print(i)
Output
H
e
l
l
o
Python String Length
In Python, we use the len() method to find the length of a string. For example
greet = 'Hello'
# count length of greet string
print(len(greet))
# Output: 5
String Membership Test
We can test if a substring exists within a string or not, using the keyword in .
print('a' in 'program') # True
print('at' not in 'battle') # False
Methods of Python String
Besides those mentioned above, there are various string methods present in Python.
Here are some of those methods:
Methods Description
upper() Converts the string to uppercase
lower() Converts the string to lowercase
partition() Returns a tuple
replace() Replaces substring inside
find() Returns the index of the first occurrence of substring
rstrip() Removes trailing characters
split() Splits string from left
startswith() Checks if string starts with the specified string
isnumeric() Checks numeric characters
index() Returns index of substring
Example of String Methods
Python String upper()
The upper() method converts all lowercase characters in a string into uppercase
characters and returns it.
Example
message = 'python is fun'
# convert message to uppercase
print(message.upper())
# Output: PYTHON IS FUN
Syntax of String upper()
The syntax of upper() method is:
string.upper()
If no lowercase characters exist, it returns the original string.
Example 1: Convert a string to uppercase
# example string
string = "this should be uppercase!"
print(string.upper())
# string with numbers# all alphabets should be lowercase
string = "Th!s Sh0uLd B3 uPp3rCas3!"
print(string.upper())
Output
THIS SHOULD BE UPPERCASE!
TH!S SH0ULD B3 UPP3RCAS3!
Example 2: How upper() is used in a program?
# first string
firstString = "python is awesome!"
# second string
secondString = "PyThOn Is AwEsOmE!"
if(firstString.upper() == secondString.upper()):
print("The strings are same.")
else:
print("The strings are not same.")
Output
The strings are same.
Python String lower()
The lower() method converts all uppercase characters in a string into lowercase
characters and returns it.
Example
message = 'PYTHON IS FUN'
# convert message to lowercase
print(message.lower())
# Output: python is fun
Syntax of String lower()
The syntax of lower() method is:
string.lower()
If no uppercase characters exist, it returns the original string.
Example 1: Convert a string to lowercase
# example string
string = "THIS SHOULD BE LOWERCASE!"
print(string.lower())
# string with numbers# all alphabets should be lowercase
string = "Th!s Sh0uLd B3 L0w3rCas3!"
print(string.lower())
Output
this should be lowercase!
th!s sh0uld b3 l0w3rcas3!
Example 2: How lower() is used in a program?
# first string
firstString = "PYTHON IS AWESOME!"
# second string
secondString = "PyThOn Is AwEsOmE!"
if(firstString.lower() == secondString.lower()):
print("The strings are same.")
else:
print("The strings are not same.")
Output
The strings are same.
Python String partition()
The syntax of partition() is:
string.partition(separator)
partition() Parameters()
The partition() method takes a string parameter separator that separates the string at
the first occurrence of it.
Return Value from partition()
The partition method returns a 3-tuple containing:
the part before the separator, separator parameter, and the part after the
separator if the separator parameter is found in the string
the string itself and two empty strings if the separator parameter is not found
Example: How partition() works?
string = "Python is fun"
# 'is' separator is found
print(string.partition('is '))
# 'not' separator is not found
print(string.partition('not '))
string = "Python is fun, isn't it"
# splits at first occurence of 'is'
print(string.partition('is'))
Output
('Python ', 'is ', 'fun')
('Python is fun', '', '')
('Python ', 'is', " fun, isn't it")
Python String replace()
The replace() method replaces each matching occurrence of a substring with another string.
Example
text = 'bat ball'
# replace 'ba' with 'ro'
replaced_text = text.replace('ba', 'ro')
print(replaced_text)
# Output: rot roll
replace() Syntax
Its syntax is:
str.replace(old, new [, count])
replace() Arguments
The replace() method can take a maximum of three arguments:
old - the old substring we want to replace
new - new substring which will replace the old substring
count (optional) - the number of times you want to replace the old substring with
the new string
Note: If count is not specified, the replace() method replaces all occurrences of
the old substring with the new string.
replace() Return Value
The replace() method returns a copy of the string where the old substring is replaced
with the new string. The original string remains unchanged.
If the old substring is not found, it returns a copy of the original string.
Example 1: Using replace()
song = 'cold, cold heart'
# replacing 'cold' with 'hurt'
print(song.replace('cold', 'hurt'))
song = 'Let it be, let it be, let it be, let it be'
# replacing only two occurrences of 'let'
print(song.replace('let', "don't let", 2))
Output
hurt, hurt heart
Let it be, don't let it be, don't let it be, let it be
More Examples on String replace()
song = 'cold, cold heart'
replaced_song = song.replace('o', 'e')
# The original string is unchanged
print('Original string:', song)
print('Replaced string:', replaced_song)
song = 'let it be, let it be, let it be'
# maximum of 0 substring is replaced# returns copy of the original string
print(song.replace('let', 'so', 0))
Output
Original string: cold, cold heart
Replaced string: celd, celd heart
let it be, let it be, let it be
Python String find()
The find() method returns the index of first occurrence of the substring (if found). If not
found, it returns -1.
Example
message = 'Python is a fun programming language'
# check the index of 'fun'
print(message.find('fun'))
# Output: 12
find() Return Value
The find() method returns an integer value:
If the substring exists inside the string, it returns the index of the first occurence
of the substring.
If a substring doesn't exist inside the string, it returns -1.
quote = 'Let it be, let it be, let it be'
# first occurance of 'let it'(case sensitive)
result = quote.find('let it')
print("Substring 'let it':", result)
# find returns -1 if substring not found
result = quote.find('small')
print("Substring 'small ':", result)
# How to use find()
if (quote.find('be,') != -1):
print("Contains substring 'be,'")
else:
print("Doesn't contain substring")
Output
Substring 'let it': 11
Substring 'small ': -1
Contains substring 'be,'
Escape Sequences in Python
The escape sequence is used to escape some of the characters present inside a string.
Suppose we need to include both a double quote and a single quote inside a string,
example = "He said, "What's there?""
print(example) # throws error
Since strings are represented by single or double quotes, the compiler will treat "He
said, " as a string. Hence, the above code will cause an error.
To solve this issue, we use the escape character \ in Python.
# escape double quotes
example = "He said, \"What's there?\""
# escape single quotes
example = 'He said, "What\'s there?"'
print(example)
# Output: He said, "What's there?"
Here is a list of all the escape sequences supported by Python.
Escape Sequence Description
\\ Backslash
\' Single quote
\" Double quote
\a ASCII Bell
\b ASCII Backspace
\f ASCII Formfeed
\n ASCII Linefeed
\r ASCII Carriage Return
\t ASCII Horizontal Tab
\v ASCII Vertical Tab
\ooo Character with octal value ooo
\xHH Character with hexadecimal value HH
Python String Formatting (f-Strings)
Python f-Strings makes it easy to print values and variables. For example,
name = 'Cathy'
country = 'UK'
print(f'{name} is from {country}')
Output
Cathy is from UK
Here, f'{name} is from {country}' is an f-string.
This new formatting syntax is powerful and easy to use. From now on, we will use f-
Strings to print strings and variables.
Python str()
The str() method returns the string representation of a given object.
Example
# string representation of Adam
print(str(5367))
# Output: 5367
str() Return Value
The str() method returns:
a printable string representation of a given object
string representation of a given byte object in the provided encoding
Example 1: Python() String
# string representation of Luke
name = str('Luke')
print(name)
# string representation of an integer 40
age = str(40)
print(age)
# string representation of a numeric string 7ft
height = str('7ft')
print(height)
Output
Luke
40
7ft
In the above example, we have used the str() method with different types of
arguments like string, integer, and numeric string.
Python String Interpolation
String interpolation is a process substituting values of variables into placeholders in a
string. For instance, if you have a template for saying hello to a person like "Hello
{Name of person}, nice to meet you!", you would like to replace the placeholder for
name of person with an actual name. This process is called string interpolation.
f-strings
Python 3.6 added new string interpolation method called literal string interpolation and
introduced a new literal prefix f . This new way of formatting strings is powerful and
easy to use. It provides access to embedded Python expressions inside string
constants.
Example 1:
name = 'World'
program = 'Python'
print(f'Hello {name}! This is {program}')
When we run the above program, the output will be
Hello World! This is Python
In above example literal prefix f tells Python to restore the value of two string
variable name and program inside braces {} . So, that when we print we get the above
output.
This new string interpolation is powerful as we can embed arbitrary Python expressions
we can even do inline arithmetic with it.
Example 2:
a = 12
b = 3
print(f'12 multiply 3 is {a * b}.')
When we run the above program, the output will be
12 multiply 3 is 36.
In the above program we did inline arithmetic which is only possible with this method.
%-formatting
Strings in Python have a unique built-in operation that can be accessed with
the % operator. Using % we can do simple string interpolation very easily.
Example 3:
print("%s %s" %('Hello','World',))
When we run the above program, the output will be
Hello World
In above example we used two %s string format specifier and two
strings Hello and World in parenthesis () . We got Hello World as output. %s string format
specifier tell Python where to substitute the value.
String formatting syntax changes slightly, if we want to make multiple substitutions in a
single string, and as the % operator only takes one argument, we need to wrap the right-
hand side in a tuple as shown in the example below.
Example 4:
name = 'world'
program ='python'
print('Hello %s! This is %s.'%(name,program))
When we run the above program, the output will be
Hello world! This is python.
In above example we used two string variable name and program . We wrapped both
variable in parenthesis () .
It’s also possible to refer to variable substitutions by name in our format string, if we
pass a mapping to the % operator:
Example 5:
name = 'world'
program ='python'
print(‘Hello %(name)s! This is %(program)s.’%(name,program))
When we run the above program, the output will be
Hello world! This is python.
This makes our format strings easier to maintain and easier to modify in the future. We
don’t have to worry about the order of the values that we’re passing with the order of
the values that are referenced in the format string.
Str.format()
In this string formatting we use format() function on a string object and braces {} , the
string object in format() function is substituted in place of braces {} . We can use
the format() function to do simple positional formatting, just like % formatting.
Example 6:
name = 'world'
print('Hello, {}'.format(name))
When we run the above program, the output will be
Hello,world
In this example we used braces {} and format() function to pass name object .We got the
value of name in place of braces {} in output.
We can refer to our variable substitutions by name and use them in any order we want.
This is quite a powerful feature as it allows for re-arranging the order of display without
changing the arguments passed to the format function.
Example 7:
name = 'world'
program ='python'
print('Hello {name}!This is{program}.'.format(name=name,program=program))
When we run the above program, the output will be
Hello world!This is python.
In this example we specified the variable substitutions place using the name of variable
and pass the variable in format() .
Key Points to Remember:
1. %-format method is very old method for interpolation and is not recommended to
use as it decrease the code readability.
2. In str.format() method we pass the string object to the format() function for string
interpolation.