Understanding Strings In Python

Understanding Strings In Python
Understanding Strings In Python

Introduction

No matter if you’re vegetarian or non-vegetarian, kebabs are a bite almost no one can resist. 

GIF Source: GIPHY

I hope I didn’t make you too hungry because now we will understand the idea of string in Python using the example of a kebab.

There are pieces of meat or vegetables in kebabs on a skewer; a string is a sequence of characters. Let’s visualise this analogy with the help of the picture below. 

There are pieces of meat or vegetables in kebabs on a skewer; a string is a sequence of characters. Let’s visualise this analogy with the help of the picture below.

Now, as in other programming languages, a string is stored in the computer memory as an array of characters as follows:

Note: It is essential to know that Python does not have any character variable compared to other programming languages. Instead, characters are strings with unit length in Python.

Therefore, on combining the two facts stated above,

  • A string can be defined as a sequence of characters stored in an array. 
  • We now know what a string is, but that is just some bookish definition. 

Let us learn about the practicability of strings in Python in the article ahead.

Creating Strings in Python

In Python, strings are created using single quotes (‘ ‘) or double quotes (“ “). 

blog banner 1

The general syntax to create a string variable is:

variable_name = ''

OR

variable_name = ""

An example would be,

str = "TEMPTING"

In Python, strings can contain not only a word but also multiple lines. 

The syntax for a multi-line Python string is:

str = ‘‘‘It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair, we had everything before us, we had nothing before us, we were all going direct to Heaven, we were all going direct the other way--in short, the period was so far like the present period, that some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only.’’’

Now that we know how to create strings in Python, we will learn to access their characters.

Accessing Strings in Python

1. Through indexing

As we already learnt, In Python, strings are stored in an array. So, accessing the characters in a string is the same as accessing the elements in an array, that is, through indexing.

Remember, the indexing starts from 0 in Python.

Therefore, the general syntax is:

string_name[index_position]

For example, according to the indexing shown below, to access a letter, let’s say, ‘P’ we will use the following syntax:

str = “TEMPTING”
str[3]

Python also allows negative indexing to access the characters in reverse order.

The negative indexing for the example above is as follows:

Therefore, the letter ‘P’ can also be accessed as follows:

str[-5]

2. Through looping

Another method to access the elements in an array is by iterating through it

using loops. 

Doing that in Python is easy and is as follows using for loop:

str = "TEMPTING"
for letter in str:
	print(letter)

Output:

T
E
M
P
T
I
N
G

3. Through slicing

We know that as an English word, slicing means cutting out a small part. 

In Python, it means the same too! Therefore slicing a string in Python means getting a small part out of the entire string, i.e., substrings of a string

The syntax to find substring in Python is as follows:

String_name[starting_index:ending_index:interval]

 Note: 

  • By default, the starting_index is 0, ending_index is the length of the string, and the interval is 1.
  • It’s not mandatory to give all three values if we omit any one of these, Python considers its default value.
  • Slicing is always done till ending_index-1.

To understand this better, let us consider the below string again.

Example 1:

str[::]

The result of the above slicing will be “TEMPTING”, Yes the whole string because it takes the default values of all three.

Example 2:

str[2:8:2]

If we match the snippet with the index, the starting index is 2, the ending index is 8, but it will run till ending_index-1, i.e. 7, and the interval is 2. Thus, it should print every second character, starting from the 2nd index up to the 7th index.

Hence, the result of the slicing will be “MTN”,i.e. the values at index(2,4,6)

Example 3:

We can do slicing using the negative index as well; let’s see how using the below example:

str[3:-2:1]

As shown in the diagram above, The output of the above snippet will be “PTI” because it starts at 3 and goes until endindex-1, i.e., -2-1=3 with an interval of 1.

Example 4: You know we can reverse the string using slicing. Yes, let’s see how!

str[::-1]

The above snippet will reverse the whole string and print “GNITPMET”.

Curious about substrings in Python? You can also read more about them, like Python substring after a character here.

Changing Strings in Python

We have already learnt a lot about strings, but now the question arises can I reassign letters in strings in Python with a different value?

GIF Source: GIPHY

If you guessed no, you are correct!

GIF Source: GIPHY

Strings in Python are immutable, i.e., we cannot change them. 

For example, if we run the following:

str = "TEMPTING"
str[0] = "K"

We will get a TypeError as shown below:

TypeError: 'str' object does not support item assignment

We can, however, reassign the string variable with an entirely different value like this:

str = "TEMPTING"
str = "YUMMY"

String Methods in Python

Accessing the elements is not the only thing you can do in Python. Python also offers many built-in methods to process strings and use them, but before seeing some commonly used methods, we should learn about the format( ) method

What comes to your mind when you hear the word format? 

If you’re thinking of a sentence or a paragraph with blanks for you to fill in, you’re on the right track. The format() method formats the specified value(s) and inserts them inside the string’s placeholder.

The placeholder is defined using curly brackets: {}. In simple words, it is used to fill in blanks in a string with some values. 

The syntax to use format() method is as follows:

"Any sentence {variable1} more text {variable2}".format(variable1 = "DATA", variable1 = “DATA”)

OR

"Any sentence {0} more text {1}.".format("DATA", “DATA”)

OR

"Any sentence {} more text {}.".format("DATA", "DATA")

For example, you may want to print the name and age of a few people stored in a list, which can easily be done in a single line as follows:

name = ["A", "B", "C"]
age = [19, 20, 21]
for i in range(3):
  print("My name is {0} and age is {1}.".format(name[i],age[i]))

Output:

My name is A and age is 19.
My name is B and age is 20.
My name is C and age is 21.

Now, let us see some other string methods in Python.

MethodSyntaxDescription
len( )len(string_name)It returns the length of a string.
capitalize( )string_name.capitalize( )It capitalizes the string.
count( )string_name.count(str)It returns the number of occurrences of str present in the string.
endswith( )string_name.endswith(str)It returns true or false based on the presence of str at the end of the string.
find( )string_name.find(str)It returns the starting index position of the first occurrence of str in the given string. In other words, it is used for a Python substring search. 
isalpha( )string_name.isalpha( )Checks if all the elements in the string are alphabets.
isdigit( )string_name.isdigit( )Checks if all the elements in the string are numbers.
lower( )string_name.lower( )Returns the string in lower case.
replace( )string_name.replace(str1,str2)Returns a string in which all the occurrences of str1 are replaced with str2.
split( )string_name.split(separator)Returns a list containing the strings separated by a separator.
strip( )string_name.strip( )Returns the string after removing blank spaces at the beginning and end of the string.
swapcase( )string_name.swapcase( )Returns a string where the lower case letters become upper case and vice-versa.
upper( )string_name.lower( )Returns the string in upper case.
title( )string_name.title( )Returns the string where the first letter of each word is in upper case.

These are just a few of the commonly used methods for strings in Python. There are many more left for you to explore while coding.  You can also lookup more built-in string methods in Python’s official documentation.

Frequently Asked Questions

Do inputs in Python get initialised as a string by default?

Yes, any input taken from the user in Python gets initialised as a string if not mentioned otherwise.

Do the string methods in Python change the initial value of the variable?

No, any string method in Python returns new values and does not change the original string.

Why are strings in Python immutable?

To avoid unnecessary bugs, strings are made immutable so that even by mistake, programmers cannot change the contents of the object.

Are Python strings a list?

No, Python strings are not a list, but we can convert them to a list in the following manner:
list(string_name)

How can we sort the letters in a string in alphabetical order?

The letters in a string can be sorted alphabetically following the given syntax:
sorted(string_name)

Key Takeaways

After reading this article, we know all about strings in Python. We learnt how to create and access strings. We also got to see a couple of commonly used string methods in Python. 

Now that we know all of these, we need to put our knowledge to use by practising coding questions. You can find a wide range of interview questions specifically on strings at CodeStudio

Apart from that, you can also find many DSA questions typically asked in interviews at big MNCs there. This will help you keep efficient coding techniques at your fingertips and provide you with interview experiences from scholars in large product-based organisations. 

By Neelakshi Lahiri