Python Strings Masterclass 101 – Introduction to Strings in Python For Absolute Beginners
This article was published as a part of the Data Science Blogathon
“Our universe exists along with other infinite universes. We are connected to those universes with strings”. I know what you are thinking about. It’s a famous quote from a web series named “Dark”.
If we a take look at our daily routine from the start of the day to the end, what are we essentially dealing with?
For example. Checking our social media feeds, Having a conversation on Whatsapp, checking for a particular location by typing location name on Google maps, and many more like this!.
Essentially all of these daily activities involved working with what is known as “string” in the programming realm. This is going to be our topic for this article. In this article, we are going to discuss Python strings and their implementation in Python.
In this article, we are going to learn about string data types in Python along with their practical implementation. Hence following are the pre-requisites for the same:
1.Ananconda distribution should be installed on your computer
2.Jupyter notebook should be installed on your computer(This will be installed automatically once anaconda distribution is installed).
What are strings in Python?
You might have a question here – “Why I am seeing an image of string here?”.
Well, let me relate this image to our definition of strings. From a definition perspective, strings are basically a sequence of characters. Now to understand this concept easily, let’s assume that string is basically a thread that is passing through each character and thus holding them together. Just like a string attached to the guitar.
For example. “ABCDEFG”. This is basically an example of a string. Here each individual word like A, B, C, D…etc are known are characters and together those characters lead to the formation of string. easy-peasy!.
Now let’s create our first string in Python String.
Code for creating a string in Python:
my_str = "Python"
Checking created string in Python:
As we can see in the above codes, we have created a string named Python and store it in a variable named my_str. When we are viewing the contents of the my_str variable, we are seeing ‘Python’ as output here.
You might be having a query here. Why there are quotes around string? Well, stay tuned for this :). We are going to see this further down the road in this article.
Single, Double, Triples quotes in Python
From my experience, I have seen that there is a lot of confusion regarding this topic. In Python, packing a string in quotes is known as enclosing a string. In Python, there are 3 ways of enclosing a string:
3 ways of enclosing strings in Python:
1.Enclosing string in Single quotes
2.Enclosing string in double quotes
3.Enclosing string in triple quotes
Code for enclosing the string in single quotes:
‘String enclosed in Single quotes’
As we can see in the above code, we have enclosed our string in single quotes. Now let’s check the inclusion of string in double-quotes.
Code for enclosing the string in double-quotes:
“String enclosed in double quotes”
As we can see here that our string is enclosed in double quotes here. Now here there is one important thing to remember. Even though we have enclosed our string either in single-quotes or double-quotes, Python’s internal syntax engine will automatically convert those into single quotes. so whether our input string is enclosed in single or double quotes, in output we will always be seeing string in single quotes.
Now you might have a question. What’s the use case for string enclosed in triple quotes?
Well, a triple quote string usually represents a multiline string.
Code for enclosing the string in triple-quotes:
"""Strings enclosed in triple quotes"""
‘Stringsnenclosed inntriple quotes’
Here in the output, we can see a character like “n”.This is something known as a new-line character. In our multi-line string, whenever we are seeing a new line in the string, this character is introduced at that respective position.
Accessing a particular character in the string
Now we have seen what is string and how it is represented in Python. What if we want to access a particular character from the string?
In strings, a particular character of the string can be assigned using an index position.
As we can see in the above image, for each character a number is assigned inside the computer’s memory. And these numbers are basically known as indexes. Using those indexes, we can access individual characters of the string.
Code for accessing a particular character of the string:
As we can see here, we have accessed a character named “E” from our string using index position 1. Why 1?. Because 1 is the index position that is associated with our character “E”. Always remember that in Python, the index always starts from 0!
String methods in Python
Python is among one the few languages that support Object-Oriented Programming.
Now one of the basic principles in object-oriented language is that everything is an object and that object will be of a particular class type. In the same context, here whatever strings we are creating are basically objects which belong to a class named “string” in Python.
Now you might be having another query. Why we are mentioning the term “methods” here?
Because methods are something that is associated only with the respective objects. Here in the context of strings, we are going to see lots of functions. Since these functions are associated with an object (which is the string that we are going to create), hence the term method.
Let’s check some of the methods that can be applied to the string object.
Upper Method for converting the string into upper case
This method is responsible for converting the case of the string from lower case to upper case
Code for converting the string into the upper case:
From the above code, we can see that our string is now converted from lower case to upper case.
Lower Method for converting the string into lower case
Just like the upper method, there is a lower method as well. As the name itself suggests, this method is responsible for converting strings into lower case.
Code for converting the string into the lower case:
Computing length of the string
In Python, a string object has a built-in method that is used for computing the length of the string. This method is known as len() method. Let’s compute the length of our string using len() method.
Code for computing length of the string:
As we can see in the above code, len() method has computed the length of the string and represented it as the number in the output.
Removing whitespaces from the string using strip method
What is meant by whitespace?. In simple terms, whitespace means space :).
In order to remove spaces from the string, the string object has a dedicated method called strip. The strip method is used to remove any whitespace which is present in the string.
Code for removing whitespaces from the string using strip method:
" HELLO ".strip(" ")
These are some of the commonly used methods for strings. Now it’s time for PRO tips 🙂
So now we have a good understanding of strings, how to implement those in python. Also, we now have enough knowledge about commonly used string methods in Python. Now it’s time to learn few PRO tricks regarding strings.
Reversing a string
This is one of the favorite questions asked in the Python interview. Usually, in other programming languages, this task can be achieved by using loops. However, in Python, we can achieve this task by using just a single line of code. Ready for this? Well here is the code for reversing a string in Python
Code for reversing a string in Python:
I am sure this is going to be your reaction
Now let’s understand this code. As you can see in our code, in square brackets there is something like”::“. This particular expression is instructing python to start from the beginning until the end of the string. Now, -1 indicates the last character. So basically when python is interpreting our code, it is going from the beginning to the end of the string and then from the end traversing our string until the beginning using the last character as a source.
Joining a string
Imagine you have a string like this – “HELLO”. Now, what if we have to convert this string into something like this “H_E_L_L_O”. In order to achieve this, we are going to use a method named “join”. This method basically takes two strings and merges them together to form a single string.
Code for Joining two strings together:
As you can see here, the join method has accepted two strings – “_” and “HELLO” as input and it merged them together to form a new resultant string.
Counting number of occurrences of character within the string
Interested in counting how many times a character appeared in a string? Want Python to do this job for you?
Well, then Python has an answer for everything. In Python, there is a method named count which will count the number of occurrences of a character in a string.
Code for counting the number of occurrences of a character in the string:
As we can see here, the count method has correctly returned the number of occurrences of character “S” in the string which is 5 in this case. The only argument that we have passed here is the character which is to be counted.
Well, that’s it. This is everything that you need to know about strings as a beginner.
Please share this article with your friends and colleagues.
The media shown in this article are not owned by Analytics Vidhya and is used at the Author’s discretion.