Python Strings

In python, string is a sequential collection of characters, and it is an object of python’s built-in class ‘str’. In python, the strings are represented by enclosing the string characters using quotes, i.e., either a single quote ('), double quote ("), or triple quote (''' or """) as long as the starting and ending of the quotes are same.

 

Following is the example of creating the strings in python using different quotes.

 

a = 'Hi'

b = "Welcome to Tutlane"

c = '''Learn Python'''

d = """Best Learning Resource"""

print(a)

print(b)

print(c)

print(d)

print(type(a))

print(type(b))

print(type(c))

print(type(d))

If you observe the above example, we created different variables (a, b, c, d) by assigning the string types with different quotes. Here, we used print() function to print string values and the type() function to know the type of variables.

 

When you execute the above python example, you will get the result like as shown below.

 

Hi

Welcome to Tutlane

Learn Python

Best Learning Resource

<class 'str'>

<class 'str'>

<class 'str'>

<class 'str'>

If you observe the above result, the type of variables (a, b, c, d) returned as str.

Multiline Strings

In python, the triple quotes (''' or """) are useful to represent the multiline strings. By using triple quotes (''' or """), you can spread the single statement content to multiple lines based on your requirements.

 

Following is the example of using triple quotes (''' or """) to create the multiline strings in python.

 

a = '''Learn Python

with examples'''

b = """Best learning resource

for programming"""

print(a)

print(b)

If you observe the above example, we created multiline strings using triple quotes (''' or """).

 

When you execute the above python program, you will get the result like as shown below.

 

Learn Python

with examples

Best learning resource

for programming

Access String Characters

Same like other programming languages, you can access the string characters in python by using index positions.

 

Following is the example of getting the string characters using an index position in python.

 

a = "Welcome to Tutlane"

print(a[0])

print(a[5])

print(a[11])

print(a[15])

If you observe the above example, we are trying to access the string characters at different index positions (0, 5, 11, 15) in python.

 

When you execute the above python program, you will get the result like as shown below.

 

W

m

T

a

If you observe the above result, we are getting the string characters from the left (first item) to the right (last item), and the index position starts from 0. If you want to get string characters from the right (last item) to the left (first), you need to use negative indexing.

 

The index of -1 refers to the last character of the string. Following is the example of getting the string characters starting from the end of the string using negative indexing in python.

 

a = "Welcome to Tutlane"

print(a[-1])

print(a[-3])

print(a[-7])

print(a[-18])

If you observe the above example, we are getting string characters from the end of the string using different negative index positions (-1, -3, -7, -18).

 

When you execute the above python program, you will get the result like as shown below.

 

e

a

T

W

In python, if you try to access the string characters using index values outside of the index range, you will get IndexError.

 

Following is the example of accessing the string characters with index values that are outside of the range in python.

 

a = "Welcome to Tutlane"

print(a[22])

If you observe the above example, we are trying to access the string character with an index position (22) outside of a range. When you execute the above program you will get an exception like “string index outside of range”.

 

Traceback (most recent call last):

  File "D:\Python Examples\pythonstrings.py", line 2, in <module>

    print(a[22])

IndexError: string index out of range

Even if you try to access the string characters by using the index value, i.e., other than integer value, then you will get TypeError like as shown below.

 

a = "Welcome to Tutlane"

print(a[2.0])

When you execute the above python program, you will get the exception like as shown below.

 

Traceback (most recent call last):

  File "D:\Python Examples\pythonstrings.py", line 2, in <module>

    print(a[2.0])

TypeError: string indices must be integers

String Slicing

In python, if you want to access the part of a string or range of string characters, then you need to use the slicing operator [ ] by mentioning the start index and end index, separated by a colon ( : ).

 

Following is the example of getting part of a string (substring) or a range of string characters using slicing in python.

 

a = "Welcome to Tutlane"

print(a[2:6])

print(a[11:16])

print(a[3:-3])

If you observe the above example, we defined the start index and end index to get part of the string or required range of string characters.

 

When you execute the above python program, you will get the result like as shown below.

 

lcom

Tutla

come to Tutl 

If you observe the above result, we got the result strings based on the defined starting and ending index positions.

 

In python slicing syntax, it’s not mandatory to add starting and ending indexes to get the part of the strings. If you miss adding the starting index in slicing syntax, by default, it will consider the starting index as 0. Same way, if you miss adding the ending index, then by default, it will consider the end of the string.

 

Following is the example of getting the substring or part of string characters using slicing syntax in python.

 

a = "Welcome to Tutlane"

print(a[:7])

print(a[11:])

print(a[:])

If you observe the above example, we try to get the string's part by defining only the ending index, starting index, and without defining any indexes in slicing syntax.

 

When you execute the above python program, you will get the result like as shown below.

 

Welcome

Tutlane

Welcome to Tutlane

In python, if you want to exclude or remove characters from the string, you can use negative indexing to slice from the end of the string.

 

Following is the example of removing characters from the end of the string using negative indexing in python.

 

a = "Welcome to Tutlane"

print(a[:-3])

print(a[:-11])

print(a[-5:-2])

When you execute the above python program, you will get the result like as shown below.

 

Welcome to Tutl

Welcome

tla

Change or Remove String Characters

In python, strings are immutable, so it won’t allow you to change or remove characters from string once they are assigned to the variables. If you want to change the string characters, you can reassign different strings to the same variable.

 

Following is the example of changing or removing characters from string in python.

 

a = "Welcome to Tutlane"

a[3] = "d"

print(a)

If you observe the above python example, we are trying to change or remove characters from a string using a particular index position.

 

When you execute the above python example, you will get the result like as shown below.

 

Traceback (most recent call last):

  File "D:\Python Examples\pythonstrings.py", line 2, in <module>

    a[3] = "d"

TypeError: 'str' object does not support item assignment

If you observe the above result, when we try to change or remove characters from the string, we got an exception because strings are immutable.

 

As discussed, in python you are not allowed to change or remove characters from the string, but you can reassign different strings. Following is the example of assigning new values to the variables in python.

 

a = "Welcome to Tutlane"

a = "Learn Python"

print(a) #Learn Python

String Concatenation

In python, you can combine or concatenate strings by using the + operator. Following is the example of using the + operator to concatenate strings in python.

 

a = "Welcome"

b = "to"

c = "tutlane"

d = a + " " + b + " " + c

print(d) #Welcome to tutlane

If you observe the above example, we are combining multiple string variables (a, b, c) by using + operator and adding space between them by using " ".

 

In case if you want to concatenate multiple copies of the same string, then you can use the * operator like as shown below.

 

a = "Python"

print(a * 3) #PythonPythonPython

String Length

In python, the len() function is useful to get the number of characters in a string or the length of a string. Following is the example of len() function in python.

 

a = "Welcome to Tutlane"

print(len(a)) #18

If you observe the above program, we used the python len() function to get the length of a string.

Check If String Contains

In python, in and not in keywords are useful to verify whether the particular character/substring exists in the string or not.

 

Following is the example of using python in and not in keywords to check whether the string contains a particular substring/character or not.

 

a = "Welcome to Tutlane"

x = "to" in a

y = "Tutlane" not in a

print(x) #True

print(y) #False

If you observe the above example, we are verifying whether the required string characters present in the defined string variable (a) or not using in and not in keywords.

Convert to String

In python, by using the built-in str() function you can convert any object such as numbers, list, etc. to a string.

 

Following is the example of converting int to string, float to string, and complex to string using the str() function in python.

 

x = str(10) #int to string

y = str(31.54) #float to string

z = str(3j) #complex to string

print("x type: ", type(x))

print("y type: ", type(y))

print("z type: ", type(z))

If you observe the above example, we are converting numbers (int, float, complex) to string using the str() function.

 

When you execute the above python program, you will get the result like as shown below.

 

x type:  <class 'str'>

y type:  <class 'str'>

z type:  <class 'str'>

Same way, you can also convert string to int, string to float, etc. by using int(), float(), etc. functions based on your requirements.

 

Following is the example of converting the string to int, float using int(), float() functions in python.

 

x = "10"

print(type(int(x)))

print(type(float(x)))

If you observe the above example, we are converting the string to int and float by using int(), float() function.

 

When you execute the above python program, you will get the result like as shown below.

 

<class 'int'>

<class 'float'>

Escape Characters

In python, escape characters are useful when you want to include illegal characters in the string. For example, if you include either single or double quotes inside of a string, you will get a syntax error like as shown below.

 

>>> a = "Welcome to "Tutlane". Let's start learning"

  File "<stdin>", line 1

    a = "Welcome to "Tutlane". Let's start learning"

                     ^

SyntaxError: invalid syntax

You can fix this problem by using a backslash (\) escape character like as shown below. 

 

a = "Welcome to \"Tutlane\". Let's start learning"

print(a)

The above example will return the result like as shown below.

 

Welcome to "Tutlane". Let's start learning

Same as backslash (\) escape character, you can use different other escape sequence characters such as \n, \t, etc. in your python programs.

 

The following table lists the different escape sequence characters available in python.

 

CharacterDescription
\\ Backslash
\' Single Quote
\n New line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
\nnn Octal notation. Here, n is in 0-7 range.
\xnn Hexadecimal notation. Here, n is in 0-9, a-f, A-F

Following is the example of using different escape sequence characters in python strings.

 

a = 'Let\'s start learning'

b = 'D:\\PythonExamples\\strings'

c = "Learn\nPython"

d = "Learn\tPython"

e = "Learn \bPython"

f = "\x54\x55\x54"

print(a)

print(b)

print(c)

print(d)

print(e)

print(f)

If you observe the above example, we used different escape characters in strings. When you execute the above python program, you will get the result like as shown below.

 

Let's start learning

D:\PythonExamples\strings

Learn

Python

Learn    Python

LearnPython

TUT

This is how you can use escape characters in python to include the required characters in the string.

String Formatting

In python, format() method is useful to format the complex strings and numbers. The format strings will contain the curly braces { } and the format() method will use those curly braces { } as placeholders to replace with the content of the parameters.

 

Following is the syntax of format() method in python to format the strings.

 

string.format(arg1, arg2, etc.)

The python format() method will accept unlimited arguments and replace the curly brace { } placeholders with the content of the respective arguments.

 

Following is the example of formatting the strings using the format() method in python.

 

str1 = "{} to {}".format("Welcome", "Tutlane.com")

print(str1)

name = "Suresh"

age = 33

str2 = "My name is {}, and I am {} years old"

print(str2.format(name, age))

If you observe the above example, we created strings with curly brace { } placeholders and we are replacing the placeholders with required argument values using format() method.

 

When you execute the above python program, you will get the result like as shown below.

 

Welcome to Tutlane.com

My name is Suresh, and I am 33 years old

If you observe the above result, we created strings with placeholders without specifying any order, and we are not sure whether the arguments are placed in the correct order or not.

 

To make sure the arguments are placed in the correct order, you can define the positional or keyword arguments in the placeholders like as shown below.

 

# Positional arguments

str1 = "{1} to {0}".format("Tutlane.com", "Welcome")

print(str1)

# Keyword arguments

name = "Suresh"

age = 33

str2 = "My name is {x}, and I am {y} years old"

print(str2.format(y = age, x = name))

If you observe the above example, we defined the placeholders with positional and keyword arguments to specify the order.

 

When you execute the above python program, you will get the result like as shown below.

 

Welcome to Tutlane.com

My name is Suresh, and I am 33 years old

In python, you can also use optional operators (<, >, ^, etc.) to format the strings and numbers in different ways using the format() method. To learn more about formatting in python, visit string formatting in python.

Python String Methods

In python, the string object is having a set of built-in methods to perform different operations.

 

The following table lists some of the commonly used string methods in the python programming language.

 

MethodDescription
lower() It will convert the string into lowercase.
upper() It will convert the string into uppercase.
capitalize() It will convert the first character of the string to uppercase.
title() It will convert the first character of each word to uppercase.
swapcase() It will swap the cases, lowercase to uppercase, and uppercase to lowercase.
translate() It will return the translated string.
islower() It will return True if all the string characters are in lower case.
isupper() It will return True if all the string characters are in upper case.
istitle() It will return True if the string follows the rules of a title()
find() It will search for the specified string and return the first occurrence of a substring.
replace() It will replace the specified substring or character in all occurrences of the given string.
join() It is useful to concatenate all the elements of an array, list, etc. using a specified separator between each element.
split() It will split the string into a list based on the specified characters.
strip() It will return the string by removing all the trailing and leading whitespaces from the specified string.
count() It will return the number of occurrences of a specified substring in the given string.
center() It will return the centered string based on the specified positions.
encode() It will return the encoded version of the string.
partition() It is useful to split the string into three parts based on the specified substring.
format() It is useful to insert a variable or expression values into another string.
index() It is useful to return an index of the first occurrence of a specified character in the given string.
isnumeric() It is useful to identify whether the given string is numeric or not.
isalpha() It will return True if all the characters of the given string are alphabets.
isalnum() It will return True if all the characters of the given string are alphanumeric.
isdigit() It will return True if all the characters of the given string are digits.
isdecimal() It will return True if all the characters of the given string are decimals.
isspace() It will return True if all the characters of the given string are whitespaces.
startswith() It will return True if the string starts with the specified value.
endswith() It will return True if the string ends with the specified value.

In the next chapters, we will learn more about these python string methods with examples.