Strings in Python

Payal Udhani on September 1, 2022

 

What are Strings in Python?

Python string is a data type in which the programming language stores any data in a computer. Python string is an array of bytes. 

A string is a sequence of characters. It is among the most popular data types in Python. It can be created simply by enclosing characters in quotes. Strings can be created by enclosing characters inside a single quote or double quotes.

In this blog, we will try to understand how to create, update and delete the python strings. At the same time, we will also look at different operators that can be used in python strings and how escape characters make the task of specifying the strings easier.

Introduction

Python string is considered an array consisting of bytes containing Unicode characters. The Character data type is not present in Python. 

String is one of the primitive data structures and is the building block for data manipulation. It can be accessed from both directions: forward and backward. 

String literal 

A string literal is a sequence of characters forming a string. Valid syntax of string literals can be any text enclosed in single quotes, double quotes, triple quotes or triple double quotes (“““sample string”””). A multiline string should always be wrapped with triple single quotes or triple double quotes

Creating Python strings

As mentioned above, strings can be created using single, double and triple quotes. Let’s consider a small program demonstrating the creation of python string –

SampleString = 'Let us fall in love with python'

print("Python string enclosed between single quotes - ")

print(SampleString)




SampleString = "Python string is an array of bytes"

print("\nPython string enclosed between double quotes - ")

print(SampleString)




SampleString = '''Python for kids can improve the logical and creative skills'''

print("\nPython string enclosed between triple quotes - ")

print(SampleString)




SampleString = '''Codingal

   at the 

   heart'''

print("\nMultiline string creation in python - ")

print(SampleString)

The output of above-mentioned code snippet is as shown below –

Python string enclosed between single quotes
Let us fall in love with python

Python string enclosed between double quotes
Python string is an array of bytes

Python string enclosed between triple quotes
Python for kids can improve the logical and creative skills

Multiline string creation in python
Codingal
at the
heart

Accessing the characters

We can use square brackets and indexing to access the elements of the string. An index is an integer number and always starts with 0 for the first character. Python also supports negative indexing where the last element has -1 index, the second last element -2 index and so on.

There are primarily two types of errors that can be generated while accessing python strings incorrectly. In case, if we specify an index of any other datatype than integer, then it results to TypeError. The second case involves accessing the element that is not within the index range for a particular string, which results in IndexError.
Below is a sample program for demonstration of string element accessing in python –

# Program for accessing Python strings

PythonString = "Codingal"
print("Printing the complete string - ")
print(PythonString)

# Accessing first character
print("\nAccessing the first character of string - ")
print(PythonString[0])

# Accessing third character
print("\nAccessing the third character of string - ")
print(PythonString[2])

# Accessing third character using negative indexing
print("\nAccessing the third character of string - ")
print(PythonString[-1])

Execution of above program results to following output –

Priniting the complete string -
Codingal

Accessing the first character of string -
C

Accessing the third character of string -
d

Accessing the third character of string -
l

Slicing the part of string

We can access a specific part of the python string with the help of the string slicing and the operator of slicing, which is a colon (:). Moreover, we can specify one or two numbers specifying the range of characters we have to slice.
So let us have a small program demonstrating how to use slicing to access part of the string containing characters within a specific range.

# Program for accessing part of Python string using slicing

# Creating a String
PythonString = "Codingal"
print("Python string in the beginning - ")
print(PythonString)

# Retrieving the part of string containing
# characters within range of 2-6
print("\nGetting string slice of range 2 to 6 - ")
print(PythonString[2:6])

# Retrieving the part of string containing
# characters within range of third character
# to third last character
print("\nGetting string slice of range 2 to -3 - ")
print(PythonString[2:-3])

The output of the above code snippet is as shown below –

Python string in the beginning -
Codingal

Getting string slice of range 2 to 6 -
ding

Getting string slice of range 2 to -3 -
din

Manipulating strings and deleting 
Previously, manipulation containing either updating the existing string characters or deletion of the characters in string is not permissible in python strings. As string is immutable we cannot reassign the elements of string or even delete elements. However, now it is supported.

Updating element of string
Let us have a glance at how to update individual elements of the string with a small demonstration program –

# Program trying to update individual elements of string
# Due to immutable property of string it was not permissible previously.

PythonString = "Welcome to Codingal"
print("String in the beginning - ")
print(PythonString)

# First methodology to update string elements
PythonList = list(PythonString)
PythonList[2] = 'k'
UpdatedPythonString = ''.join(PythonList)
print("\nUpdated python string after modifying third character element - ")
print(UpdatedPythonString)

# First methodology to update string elements

UpdatedString = PythonString[0:2] + 'k' + PythonString[3:]
print(UpdatedString)

Execution of above program results to following output –

String in the beginnning -
Welcome to Codingal

Updated python string after modifying third character element -
Wekcome to Codingal
Wekcome to Codingal

Deleting element of string 

Let us now consider a sample program for deleting elements of string –

# Program trying to delete element of python string


PythonString = "Welcome to Codingal"
print("String in the beginning - ")
print(PythonString)

# Element deletion from original string
UpdatedPythonString = PythonString[0:2] + PythonString[3:]
print("\nResulting python string after removing the second element from it - ")
print(UpdatedPythonString)

The output of above code is –

String in the beginning -
Welcome to Codingal

Resulting python string after removing the second element from it -
Wecome to Codingal

Updating entire string

We can also go for reassigning a completely new string to the same name and accessing the updated string.
Here’s a program demonstrating updating an entire string –

# Program trying to update entire python string

PythonString = "Welcome to Codingal"
print("String in the beginning - ")
print(PythonString)

# Updating a String
PythonString = "Let's fall in love with Coding"
print("\nString after updation - ")
print(PythonString)

After execution the output of above code is as following –

String in the beginning -
Welcome to Codingal

String after updation -
Let’s fall in love with Coding

Deleting entire string in python –

There is a functionality where we can go for deleting the whole string by using the inbuilt function present in python named del keyword.
# Program trying to delete python string


PythonString = "Welcome to codingal"
print("String in the beginning - ")
print(PythonString)


del PythonString
print("\nThe deleted python string - ")
print(PythonString)

The output of above code is as shown below and showing error as the deleted string cannot be accessed and printed –

String in the beginning -
Welcome to Codingal

The deleted python string -
Traceback (most recent call last):
File "main.py", line 11, in <module>
print(PythonString)
NameError: name 'PythonString' is not defined

Escape sequences
When we have to keep a single or double quote present inside the string, creating a python string gives a syntax error if the string containing quotes is enclosed between single or double quotes.
To avoid this, we can either use triple quotes to enclose the string containing single or double quotes in it or use escape sequences.
In python, multiple escape sequence characters are supported and all of them begin with a backslash and hold different interpretations.
To allow the occurrence of quotes and slashes, they are preceded with backslash as their presence is then considered even if a string is enclosed between single or double quotes.
Let us look at the practical usage of escape sequences in python with the help of a program-

# Program for demonstrating use of escape sequences in python strings
# Initial String
PythonString = '''Let's fall in love with "Coding"'''
print("Python string enclosed in triple quotes - ")
print(PythonString)

# escape sequencing used to allow single quote presence
PythonString = 'Let\'s fall in love with "Coding"'
print("\nUsing slash to allow use of single quotes in python string")
print(PythonString)

# escape sequencing used to allow double quote presence
PythonString = "Get ready to fall in love with \"Coding\""
print("\nEscape sequence used to allow double quote - ")
print(PythonString)

# Using escape sequence character to print the
# path or address using backslash escape character
PythonString = "D:\\Desktop\\Codingal"
print("\nUsing backslash escape character to print path - ")
print(PythonString)

# using tab
PythonString = "welcome\to codingal"
print("\nUse of tab escape sequence - ")
print(PythonString)

# Using new lines
PythonString = "Welcome\nLets get ready to love coding!"
print("\nUse of tab escape sequence - ")
print(PythonString)

The output of above code is –

Python string enclosed in triple quotes

Let's fall in love with "Coding"

Using slash to allow use of single quotes in python string

Let's fall in love with "Coding"

Escape sequence used to allow double quote

Get ready to fall in love with "Coding"

Using backslash escape character to print path

D: \Desktop\Codingal
Use of tab escape sequence

welcome to codingal

Use of tab escape sequence

Welcome

Lets get ready to love coding!

Conclusion 
After reading this blog, you will get a clear understanding of how to use python strings, its creation, updating and deleting the part of string and whole python strings, operators on strings and escape sequence characters used in strings. You also became familiar with some of the popular string operator.

Python is one of the popular and versatile programming languages. It is the best programming language to start with. Coding for kids has many beneficial advantages that develop cognitive abilities as well as enhances communication skills, entrepreneurship skills, and stimulates creativity.

Python is widely used in various fields such as data analysis, machine learning, software testing and prototyping, web development, and in many other areas.

Codingal offers Python for kids course to help your child enhance cognitive, logical, and computational skills. We provide 1:1 live interactive online coding classes for kids with expert coding instructors. Along with lifetime access to course content and downloadable learning resources, to cater to every child’s need by providing a personalized journey. Try a free class today!

Sign up to our newsletter

Get the latest blogs, articles, and updates delivered straight to your inbox.

Share with your friends

Try a free class