Home » Strings In Python

Strings In Python

Strings In Python

What are Strings In Python?

Strings are one of the most fundamental data types in Python, representing sequences of characters. They are used extensively in programming for tasks such as text processing, data manipulation, and user interaction. In this comprehensive guide, we will explore everything you need to know about strings in Python, including basic operations, string methods, formatting, and advanced string manipulation techniques.

In Python, a string is a sequence of characters enclosed within single quotes (‘ ‘), double quotes (” “), or triple quotes (”’ ”’). Strings are used to represent text data or anything that you enclose between single or double quotation marks is considered a string. A string is essentially a sequence or array of textual data.

Strings are used when working with Unicode characters.

Examples:

Here are some basic examples of Python strings:


# Single quotes
name = 'Alice'

# Double quotes
message = "Hello, world!"

# Triple quotes
paragraph = '''Python is a versatile programming language.
It is used for web development, data analysis, artificial intelligence, and more.'''

Python

Example:

name = "Samuel"
print("Hello, " + name)
Python

Output:

Hello, Samuel
Python

Note: It does not matter whether you enclose your strings in single or double quotes, the output remains the same.

Sometimes, the user might need to put quotation marks in between the strings. Example, consider the sentence: He said, “I want to eat an apple”.

How will you print this statement in python?

Wrong way ❌

print("He said, "I want to eat an apple".")
Python

Output:

print("He said, "I want to eat an apple".")
                     ^
SyntaxError: invalid syntax
Python

Right way ✔️

print('He said, "I want to eat an apple".')
#OR
print("He said, \\"I want to eat an apple\\".")
Python

Output:

He said, "I want to eat an apple".
He said, "I want to eat an apple".
Python

What if you want to write multiline strings in python?

Sometimes the programmer might want to include a note, or a set of instructions, or just might want to explain a piece of code. Although this might be done using multiline comments, the programmer may want to display this in the execution of programmer. This is done using multiline strings.

Example:

receipe = """
1. Heat the pan and add oil
2. Crack the egg
3. Add salt in egg and mix well
4. Pour the mixture in pan
5. Fry on medium heat
"""
print(receipe)

note = '''
This is a multiline string
It is used to display multiline message in the program
'''
print(note)
Python

Output:

`1. Heat the pan and add oil 2. Crack the egg 3. Add salt in egg and mix well 4. Pour the mixture in pan 5. Fry on medium heat

This is a multiline string It is used to display multiline message in the program`

Operation on Strings in Python

1. Length of a String in Python

We can find the length of a string using len() function.

Example:

fruit = "Mango"
len1 = len(fruit)
print("Mango is a", len1, "letter word.")
Python

Output:

Mango is a 5 letter word.
Python

2. String as an Array

A string is essentially a sequence of characters also called an array. Thus we can access the elements of this array.

Example:

pie = "ApplePie"
print(pie[:5])
print(pie[6])	#returns character at specified index
Python

Output:

Apple
i
Python

Note: This method of specifying the start and end index to specify a part of a string is called slicing.

Example:

pie = "ApplePie"
print(pie[:5])      #Slicing from Start
print(pie[5:])      #Slicing till End
print(pie[2:6])     #Slicing in between
print(pie[-8:])     #Slicing using negative index
Python

Output:

Apple
Pie
pleP
ApplePie
Python

3. Loop through a String in Python

Strings are arrays and arrays are iterable. Thus we can loop through strings.

Example:

alphabets = "ABCDE"
for i in alphabets:
    print(i)
Python

Output:

A
B
C
D
E
Python

String Methods

Python provides a set of built-in methods that we can use to alter and modify the strings.

1. upper()

The upper() method converts a string to upper case.

Example:

str1 = "AbcDEfghIJ"
print(str1.upper())
Python

Output:

ABCDEFGHIJ
Python

2. lower()

The lower() method converts a string to upper case.

Example:

str1 = "AbcDEfghIJ"
print(str1.lower())
Python

Output:

abcdefghij
Python

3. strip()

The strip() method removes any white spaces before and after the string.

Example:

str2 = " Silver Spoon "
print(str2.strip)
Python

Output:

Silver Spoon
Python

4. rstrip()

the rstrip() removes any trailing characters.

Example:

str3 = "Hello !!!"
print(str3.rstrip("!"))
Python

Output:

Hello
Python

5. replace()

the replace() method replaces a string with another string.

Example:

str2 = "Silver Spoon"
print(str2.replace("Sp", "M"))
Python

Output:

Silver Moon
Python

6. split() :

The split() method splits the give string at the specified instance and returns the separated strings as list items.

Example:

str2 = "Silver Spoon"
print(str2.split(" "))      #Splits the string at the whitespace " ".
Python

Output:

['Silver', 'Spoon']
Python

There are various other string methods that we can use to modify our strings.

7. capitalize()

The capitalize() method turns only the first character of the string to uppercase and the rest other characters of the string are turned to lowercase. The string has no effect if the first character is already uppercase.

Example:

str1 = "hello"
capStr1 = str1.capitalize()
print(capStr1)
str2 = "hello WorlD"
capStr2 = str2.capitalize()
print(capStr2)
Python

Output:

Hello
Hello world
Python

8. center() :

The center() method aligns the string to the center as per the parameters given by the user.

Example:

str1 = "Welcome to the Console!!!"
print(str1.center(50))
Python

Output:

            Welcome to the Console!!!
Python

We can also provide padding character. It will fill the rest of the fill characters provided by the user.

Example:

str1 = "Welcome to the Console!!!"
print(str1.center(50, "."))
Python

Output:

............Welcome to the Console!!!.............
Python

9. count()

The count() method returns the number of times the given value has occurred within the given string.

Example:

str2 = "Abracadabra"
countStr = str2.count("a")
print(countStr)
Python

Output:

4
Python

10. endswith()

The endswith() method checks if the string ends with a given value. If yes then return True, else return False.

Example 1:

str1 = "Welcome to the Console !!!"
print(str1.endswith("!!!"))
Python

Output:

True
Python

Example 2:

str1 = "Welcome to the Console !!!"
print(str1.endswith("Console"))
Python

Output:

False
Python

We can even also check for a value in-between the string by providing start and end index positions.

Example:

str1 = "Welcome to the Console !!!"
print(str1.endswith("to", 4, 10))
Python

Output:

True
Python

11. find()

The find() method searches for the first occurrence of the given value and returns the index where it is present. If given value is absent from the string then return -1.

Example:

str1 = "He's name is Dan. He is an honest man."
print(str1.find("is"))
Python

Output:

10
Python

As we can see, this method is somewhat similar to the index() method. The major difference being that index() raises an exception if value is absent whereas find() does not.

Example:

str1 = "He's name is Dan. He is an honest man."
print(str1.find("Daniel"))
Python

Output:

-1
Python

12. index()

The index() method searches for the first occurrence of the given value and returns the index where it is present. If given value is absent from the string then raise an exception.

Example:

str1 = "He's name is Dan. Dan is an honest man."
print(str1.index("Dan"))
Python

Output:

13
Python

As we can see, this method is somewhat similar to the find() method. The major difference being that index() raises an exception if value is absent whereas find() does not.

Example:

str1 = "He's name is Dan. Dan is an honest man."
print(str1.index("Daniel"))
Python

Output:

ValueError: substring not found
Python

13. isalnum()

The isalnum() method returns True only if the entire string only consists of A-Z, a-z, 0-9. If any other characters or punctuations are present, then it returns False.

Example 1:

str1 = "WelcomeToTheConsole"
print(str1.isalnum())
Python

Output:

True
Python

Example 2:

str1 = "Welcome To The Console"
print(str1.isalnum())
str2 = "Hurray!!!"
print(str2.isalnum())
Python

Output:

False
False
Python

14. isalpha()

The isalnum() method returns True only if the entire string only consists of A-Z, a-z. If any other characters or punctuations or numbers(0-9) are present, then it returns False.

Example 1:

str1 = "Welcome"
print(str1.isalpha())
Python

Output:

True
Python

Example 2:

tr1 = "I'm 18 years old"
print(str1.isalpha())
str2 = "Hurray!!!"
print(str2.isalnum())
Python

Output:

False
False
Python

15. islower()

The islower() method returns True if all the characters in the string are lower case, else it returns False.

Example 1:

str1 = "hello world"
print(str1.islower())
Python

Output:

True
Python

Example 2:

str1 = "welcome Mike"
print(str1.islower())
str2 = "Hurray!!!"
print(str2.islower())
Python

Output:

False
False
Python

16. isprintable()

The isprintable() method returns True if all the values within the given string are printable, if not, then return False.

Example 1:

str1 = "We wish you a Merry Christmas"
print(str1.isprintable())
Python

Output:

True
Python

Example 2:

str2 = "Hello, \\t\\t.Mike"
print(str2.isprintable())
Python

Output:

False
Python

17. isspace()

The isspace() method returns True only and only if the string contains white spaces, else returns False.

Example 1:

str1 = "        "       #using Spacebar
print(str1.isspace())
str2 = "        "       #using Tab
print(str2.isspace())
Python

Output:

True
True
Python

Example 2:

str1 = "Hello World"
print(str1.isspace())
Python

Output:

False
Python

18. istitle()

The istitile() returns True only if the first letter of each word of the string is capitalized, else it returns False.

Example 1:

str1 = "World Health Organization"
print(str1.istitle())
Python

Output:

True
Python

Example 2:

str2 = "To kill a Mocking bird"
print(str2.istitle())
Python

Output:

False
Python

19. isupper()

The isupper() method returns True if all the characters in the string are upper case, else it returns False.

Example 1:

str1 = "WORLD HEALTH ORGANIZATION"
print(str1.isupper())
Python

Output:

True
Python

Example 2:

str2 = "To kill a Mocking bird"
print(str2.isupper())
Python

Output:

False
Python

20. replace()

The replace() method can be used to replace a part of the original string with another string.

Example:

str1 = "Python is a Compiled Language."
print(str1.replace("Compiled", "Interpreted"))
Python

Output:

Python is a Interpreted Language.
Python

21. startswith()

The endswith() method checks if the string starts with a given value. If yes then return True, else return False.

Example 1:

str1 = "Python is a Interpreted Language"
print(str1.startswith("Python"))
Python

Output:

True
Python

Example 2:

str1 = "Python is a Interpreted Language"
print(str1.startswith("a"))
Python

Output:

False
Python

We can even also check for a value in-between the string by providing start and end index positions.

Example:

str1 = "Python is a Interpreted Language"
print(str1.startswith("Inter", 12, 20))
Python

Output:

True
Python

22. swapcase()

The swapcase() method changes the character casing of the string. Upper case are converted to lower case and lower case to upper case.

Example:

str1 = "Python is a Interpreted Language"
print(str1.swapcase())
Python

Output:

pYTHON IS A iNTERPRETED lANGUAGE
Python

23. title()

The title() method capitalizes each letter of the word within the string.

Example:

str1 = "He's name is Dan. Dan is an honest man."
print(str1.title())
Python

Output:

He'S Name Is Dan. Dan Is An Honest Man.

Format Strings in Python

What if we want to join two separated strings in python?

We can perform concatenation to join two or more separate strings.

Example:

str4 = "Captain"
str5 = "America"
str6 = str4 + " " + str5
print(str6)
Python

Output:

Captain America
Python

In the above example, we saw how one can concatenate two strings. But how can we concatenate a string and an integer?

name = "Guzman"
age = 18
print("My name is" + name + "and my age is" + age)
Python

Output:

TypeError: can only concatenate str (not "int") to str
Python

As we can see, we cannot concatenate a string to another data type.

So what’s the solution?

We make the use of format() method. The format() methods places the arguments within the string wherever the placeholders are specified.

Example:

name = "Guzman"
age = 18
statement = "My name is {} and my age is {}."
print(statement.format(name, age))
Python

Output:

My name is Guzman and my age is 18.
Python

We can also make the use of indexes to place the arguments in specified order.

Example:

quantity = 2
fruit = "Apples"
cost = 120.0
statement = "I want to buy {2} dozen {0} for {1}$"
print(statement.format(fruit,cost,quantity))
Python

Output:

I want to buy 2 dozen Apples for $120.0
Python

Escape Characters

Escape Characters are very important in python. It allows us to insert illegal characters into a string like a back slash, new line or a tab.

Single/Double Quote: used to insert single/double quotes in the string.

Example:

str1 = "He was \\"Flabergasted\\"."
str2 = 'He was \\'Flabergasted\\'.'
print(str1)
print(str2)
Python

Output:

He was "Flabergasted".
He was 'Flabergasted'.
Python

1. New Line: inserts a new line wherever specified.

Example:

str1 = "I love doing Yoga. \\nIt cleanses my mind and my body."
print(str1)
Python

Output:

I love doing Yoga.
It cleanses my mind and my body.
Python

2. Tab: inserts a tab wherever specified.

Example:

str2 = "Hello \\t\\tWorld \\t!!!"
print(str2)
Python

Output:

Hello           World   !!!
Python

3. Backspace: erases the character before it wherever it is specified.

Example:

str2 = "Hello  \\bWorld !!!"
print(str2)
Python

Output:

Hello World !!!
Python

4. Backslash: used to insert a backslash into a string in python.

Example:

str3 = "What will you eat? Apple\\\\Banana"
print(str3)
Python

Output:

What will you eat? Apple\\Banana
Python

Conclusion

Strings are an essential part of Python programming, and mastering string manipulation techniques is crucial for becoming proficient in Python development. By understanding the basic operations, string methods, formatting options, and advanced manipulation techniques covered in this guide, you’ll be well-equipped to handle a wide range of string-related tasks in your Python projects. Whether you’re a beginner or an experienced programmer, strings are a fundamental building block that you’ll use extensively throughout your Python journey.

Frequently Asked Questions

Q1. What is a string in Python?

Ans: A string in Python is a sequence of characters, which can be letters, numbers, symbols, or spaces. It is enclosed within either single quotes (‘ ‘), double quotes (” “), or triple quotes (”’ ”’ or “”” “””).


Q2. How do you create a string in Python?

Ans: Strings can be created by enclosing characters within quotes. For example: pythonCopy code my_string = “Hello, World!”


Q3. How do you access characters in a string?

Ans: Characters in a string can be accessed using indexing. Python uses zero-based indexing, so the first character is at index 0. For example: pythonCopy code my_string = “Hello, World!” print(my_string[0]) # Output: H


Q4. Can you change characters in a string?

Ans: No, strings in Python are immutable, which means you cannot change the characters in a string after it has been created. However, you can create a new string with the desired modifications.


Q5. How do you find the length of a string?

Ans: You can use the len() function to find the length of a string. For example: pythonCopy code my_string = “Hello, World!” length = len(my_string)


Q6. How do you split a string into a list of substrings?

Ans: You can use the split() method, which splits a string into a list of substrings based on a delimiter. For example: pythonCopy code my_string = “Hello, World!” substrings = my_string.split(“,”) # splits at ‘,’.


Q7. How do you convert a string to uppercase or lowercase?

Ans: You can use the upper() method to convert a string to uppercase and the lower() method to convert it to lowercase. For example: pythonCopy code my_string = “Hello, World!” uppercase_string = my_string.upper() lowercase_string = my_string.lower()


Q8. How do you replace a substring within a string?

Ans: You can use the replace() method to replace occurrences of a substring with another substring. For example: pythonCopy code my_string = “Hello, World!” new_string = my_string.replace(“World”, “Python”)


Q9. How do you check if a substring exists in a string?

Ans: You can use the in keyword to check if a substring exists in a string. For example: pythonCopy code my_string = “Hello, World!” if “World” in my_string: print(“Substring found”)