Introduction to Strings in Python For Beginners

Shrish Mohadarkar 20 Mar, 2024 • 10 min read

Introduction

In programming, strings are a basic data type that hold character sequences. Working with strings is crucial for many Python tasks, ranging from simple text manipulation to intricate data processing. From basic string creation and manipulation to more complex ideas like string methods and operations, this article seeks to offer a thorough overview of understanding and using strings in Python.

This post will be very helpful whether you’re a novice learning Python or an expert programmer trying to improve your string handling abilities. In addition to covering the theoretical parts of strings, it also offers real-world examples and use cases to help you grasp the concepts. Now let’s explore the world of Python strings and discover all of their possibilities!

This article was published as a part of the Data Science Blogathon

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

my_str = "Python"
print(my_str)
Output:
'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.

Also Read: String Data Structure in Python

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

  • Enclosing string in Single quotes
  • Enclosing string in double quotes
  • 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"""
Output:
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.

Also Follow: 90+ Python Interview Questions 2024

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.

Representation of string in computer’s memory

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:

"HELLO"[1]
Output:
'E'

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:

"Hello".upper()
Output:
'HELLO'

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:

"HELLO".lower()
Output:
'hello'

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

len("Hello")
Output:
5

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(" ")
Output:
'HELLO'

As we can see in the above code, the strip method accepts one argument. The argument is basically a whitespace character that needs to be removed. In our string, we can see that there are many whitespaces present at the beginning as well as at the end of the string and hence we have passed ” ” as an argument in our strip method.

These are some of the commonly used methods for strings. Now it’s time for PRO tips 🙂

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

"HELLO"[::-1]
Output:
'OLLEH'

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

Say you have a string that says “HELLO” in it. What would happen if we needed to translate this string into something like “H_E_L_L_O”? We’re going to utilize a mechanism called “join” to do this. This technique essentially creates a single string by combining two strings.

Code for Joining two strings together:

"_".join("HELLO")
Output:
'H_E_L_L_O'

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

"SSSSS".count("S")
Output:
5

Here, we can observe that the count method has accurately returned the number of times the character “S” appears in the string—in this example, five. The only argument that we have passed here is the character which is to be counted.

String Slicing in Python

Apart from the several string operations we have discussed, Python offers an effective approach for accessing substrings within a string through the use of slicing. By giving a range of character locations or indices, string slicing enables you to extract a specific piece of a string.

Syntax for String Slicing

string[start:stop:step]

Here’s what each component represents:

  • start (optional): The index position from where the slicing should begin. If omitted, it defaults to 0 (the start of the string).
  • stop (optional): The index position where the slicing should end (but not included). If omitted, it defaults to the length of the string.
  • step (optional): The step size, which determines the increment between each index for slicing. If omitted, it defaults to 1.

Examples to understand string slicing better

my_string = "Hello, World!"
print(my_string[0:5])
print(my_string[7:12])
Output:
Hello
World

In the first example, we slice the string from index 0 (inclusive) to index 5 (exclusive), retrieving the substring “Hello”. In the second example, we slice from index 7 to 12, extracting the substring “World”.

print(my_string[::2])
print(my_string[::-1])
Output:
Hlo ol!
!dlroW ,olleH

Here, we use the step parameter to skip characters. In the first example, we slice the entire string with a step of 2, resulting in “Hlo ol!”. In the second example, we use a step of -1 to reverse the string, yielding “!dlroW ,olleH”.

Advanced Slicing Techniques

You can combine slicing with string methods for more advanced operations. For example, to remove leading/trailing whitespaces and newlines from a string, you can use:

my_string = " Hello, World! \n"
print(my_string.strip()[1:-1])
Output:
 Hello, World!

In this example, we slice the string from index 1 to the second-last index to remove the remaining whitespaces after first using the strip() method to remove newlines and leading/trailing whitespaces.

String manipulation is made simple and flexible with the help of an effective technique called string slicing. It can be used in conjunction with other string operations and methods to effectively handle a variety of string-related jobs in your Python scripts.

Common String Operations

There are many different operations and methods available in Python that can be used with strings. Some of the most popular ones are the ones listed below:

Concatenation

You can combine two or more strings using the + operator.

greeting = "Hello, "
name = "Ram"
message = greeting + name
print(message)
Output:
Hello, Ram

Repetition

You can repeat a string by using the * operator.

repeated_string = "Python " * 3
print(repeated_string)
Output:
Python Python Python

Membership Testing

Python offers a wide range of methods and operations that can be applied to strings. The following are a few of the most widely used ones:

text = "The quick brown fox"
print("quick" in text) # Output: True
print("lazy" not in text)
Output:
True

Iteration

Since strings are sequences, you can iterate over them using a for loop.

for char in "Hello":
print(char)
Output:
H

e

l

l

o

Common String Methods

Python’s string class provides a rich set of methods for various operations. Some commonly used ones include:

  • upper() and lower() for case conversion
  • strip() for removing leading/trailing whitespaces
  • replace() for replacing substrings
  • split() for splitting a string into a list based on a delimiter
  • join() for joining a list of strings into a single string
message = " Hello, World! "
print(message.strip()) # Output: "Hello, World!"
print(message.lower()) # Output: " hello, world! "
print(message.replace("World", "Python"))
Output:
Hello, Python! 

These are but a handful of the numerous string operations and methods that Python offers. You can manipulate and transform strings to fit your needs in a variety of programming jobs by becoming proficient with these operations.

String Formatting

In Python, you can format strings in several ways, allowing you to embed values or expressions within strings. Here are some common string formatting techniques:

%-formatting (Old Style)

This technique uses the % operator to format strings.

name = "Ram"
age = 25
formatted_string = "My name is %s and I'm %d years old." % (name, age)
print(formatted_string)
Output:
My name is Ram and I'm 25 years old.

str.format() method

This method provides a more flexible way to format strings.

name = "Ram"
age = 25
formatted_string = "My name is {} and I'm {} years old.".format(name, age)
print(formatted_string)
Output:
My name is Ram and I'm 25 years old.

f-strings (Python 3.6+)

Introduced in Python 3.6, f-strings (formatted string literals) provide a concise and readable way to format strings.

name = "Ram"
age = 25
formatted_string = f"My name is {name} and I'm {age} years old."
print(formatted_string)
Output:
My name is Ram and I'm 25 years old.

These string formatting techniques allow you to embed values, expressions, or even function calls within strings, making it easy to generate dynamic and customized output.

In addition to these basic techniques, Python also provides more advanced string formatting options, such as string templates and custom formatters, which can be useful in specific scenarios.

By mastering string formatting in Python, you can create clear, readable, and dynamically generated strings for various purposes, such as logging, user interfaces, or data manipulation.

Conclusion

Throughout this comprehensive guide, we explored the world of strings in Python, covering creation, manipulation, slicing, and formatting techniques. We learned about common string operations like concatenation, repetition, membership testing, and iteration. Additionally, we discovered powerful string methods for tasks like case conversion, whitespace removal, substring replacement, and splitting. Furthermore, we delved into various string formatting approaches, including %-formatting, str.format(), and the modern f-strings, enabling dynamic and expressive string construction. By mastering these concepts and techniques, you’ll be well-equipped to tackle a wide range of string-related tasks efficiently and elegantly in your Python programming endeavors, whether it’s text processing, data manipulation, or generating user-friendly outputs.

Frequently Asked Questions?

Q1. What are strings in Python?

A. Strings are sequences of characters in Python, enclosed in single (”), double (” “), or triple (”’ ”’ or “”” “””) quotes. They’re immutable, meaning their contents cannot be changed once created.

Q2. How many strings are there in Python?

A. Python doesn’t impose a limit on the number of strings that can be created. You can create as many strings as needed, depending on available memory.

Q3. What is a string and example?

A. A string is a data type used to represent text. Example: “Hello, World!” or ‘Python Programming’.

Q4. What is string formatting in Python?

A. String formatting involves creating formatted strings, replacing placeholders with actual values. This can be done using methods like format(), f-strings (formatted string literals), or the % operator.

The media shown in this article are not owned by Analytics Vidhya and is used at the Author’s discretion.

Shrish Mohadarkar 20 Mar 2024

Frequently Asked Questions

Lorem ipsum dolor sit amet, consectetur adipiscing elit,

Responses From Readers

Clear

Erik Kapaber
Erik Kapaber 28 May, 2021

Ah yes, a masterclass for absolute beginners ;)

Related Courses

Python
Become a full stack data scientist