What is String in Python and How to Implement Them?

Tutorial Playlist

Table of Contents

Strings in Python

If you want to learn Python, then strings are one of the major key points that you need to advance to excel in your Python journey. Strings in Python allow you to store and modify text easily. Strings have wide application areas from simple text processing to complex operations.

 

What is Strings in Python?

strings_in_python

Strings in Python are characters, symbols, or letters wrapped within single, double, or triple quotes. You can represent anything in the form of strings like numbers, words, special characters, sentences, etc. Python Strings once created can’t be altered directly, which is why they are called immutable.

Example: 

#String in Python
Text = 'Intellipaat'</pre>

Key Features of Python Strings

Python strings are very powerful, they are packed with features and are very easy to use:

  • A Python string is Immutable, which means it can’t be modified directly. If there are any changes made in the string then it will result in the creation of a new string.
  • Strings in Python are of Dynamic Size, so they adjust automatically according to the data. This saves the manual effort of developers of memory management.
  • There are many built-in methods provided by Python like split(), replace(), islower(), count(), and more. These methods make string operations easier.
  • Strings in Python are easy to use, they can be concatenated, reversed, split, and more.
  • Strings in Python are Unicode, they can handle any type of characters or emojis.

Creating a String

Creating Strings in Python is super easy. They can be created with the use of single, double, or triple quotes. Strings can handle special characters, numbers, words, sentences, emojis, etc.

 

Single Quotes: These strings are created with the use of single quotes.

# Creating strings with single quotes
Text = 'Intellipaat'

Double Quote: These strings are created with the use of double quotes.

# Creating strings with double quotes
Text = "Intellipaat"

Triple Quotes: These are easy to use in the case of multi-line strings.

# Creating strings with Triple quotes
Text = """ Learn Python
With Intellipaat """

Python String Operators

string_operators

You can perform various operations on strings in Python. These operations ease the process of modifying and manipulating strings. Following are some of the operations on strings in Python:

Finding the Length of the String

If you want to find the length of a string, Python allows you to use the len() function to count the characters of the string.

Example:

#Creating Python String
Text = "Intellipaat"

#Calculating length
Length = len(Text)

#print the length of the string
print(Length)   #Output: 11

Repetition of Strings 

String operations in Python are amazing. If you want to print a string repetitively, then it can be easily done with the * operation.

Example:

Text = "Intellipaat "
#Repetition of String
print(Text * 3)     #Output: Intellipaat Intellipaat Intellipaat 

Check for Substrings

If you want to check if the string contains a substring you’re looking for, use the in operator.

Example: 

#checking for substring
print("Learn" in "Learn with Intellipaat")  #Output: True
Start Your Journey to Python Excellence
Explore Python Like Never Before
quiz-icon

Join Strings

If you want to join two or more strings then Python allows you to do that easily with the help of join() function.

Example:

#Assigning strings
Text = ["Learn", "with", "Intellipaat"]

#joining strings
Joined_strings = " ".join(Text)
#printing the Output
print(Joined_strings)       #Output: Learn with Intellipaat

 

Accessing Characters in Strings

Python allows you to access each character of a string with the use of indexing. A string is nothing but a sequence of characters, so each character is placed at an index. So, by using these indices, we can access the characters of a string. Indexing can be of two types:

 

Positive Indexing: If you want to access characters from the beginning of the string then you use positive indexing.

Example:

#Creating String
Text = "INTELLIPAAT"

#Accessing the characters
print(Text[0])     #Output: I
print(Text[5])     #Output: L
print(Text[7])     #Output: P

 

Negative Indexing: If you want to access characters from the end of the string then you use the negative indexing.

Example:

#Creating String
Text = "INTELLIPAAT"

#Accessing the characters
print(Text[-9])     #Output: T
print(Text[-2])     #Output: A
print(Text[-7])     #Output: L

Deleting a String

In Python, once a string is created, you can not modify it because strings in Python are immutable. But, Python allows you to delete a string completely. You can do that using the del statement. If you try to access a deleted string, then it will result in an error.

Example:

#Creating a String
Text = "Intellipaat"
print(Text)   #Output: Intellipaat

#Using the del statement
del Text
print(Text)  #Output: NameError: name 'Text' is not defined

Updating a String

You know strings are immutable in Python, so you can not directly update them, but you can create a new string that contains the updated content.

Example:

#Creating a String
Text = "Intellipaat

#print the current String
print(Text)   #Output: Intellipaat

#Updating a String
updated_string = "Learn With " + Text

#print the updated String
print(updated_string)   #Output: Learn With Intellipaat

String Concatenation

If you want to combine two or more strings, then Python allows you to do that with a simple ‘+’ operator. This operation helps you combine user inputs or create dynamic outputs.

Example:

# Creating 3 Strings
Text1 = "Learn"
Text2 = "With"
Text3 = "Intellipaat"

# Combining these strings
combined_string = Text1 + " " + Text2 + " " + Text3

# Print the updated string
print(combined_string) # Output: Learn With Intellipaat
Become a Data Science Expert
Unlock Data Science Mastery Here
quiz-icon

Python String Methods

There are multiple operations that are to be performed on strings, like searching, modifying, accessing, slicing, and formatting. Python provides a wide range of easy-to-use methods that can be used directly to perform these operations efficiently.

 

Following are some of these methods:

 

Method Description
capitalize() This method is used to convert the first character of a string to uppercase.
casefold() This method converts all the characters to lowercase, but it is more effective than the lower() method because it is case-insensitive.
center(width, char) This method is used to center the string within the limit specified as the parameter and fill it with the character specified as the parameter.
count(substring) This method counts the number of times a substring appears in a string. This method can also be used with some more parameters as needed.
endswith(suffix) This method is used to check if a string ends with a specified suffix. We can also use some more parameters as needed like the start and end of the string.
find(substring) This method is used to find the index of the first occurrence of the substring in the main string. It returns -1 if the substring is not found.
format(args) This method is used to format strings using placeholders.
isalnum() This method checks if all the characters of a string are alphanumeric.
isalpha() This method is used to check if all the characters of a string are alphabets.
isdigit() This method is used to check if all the characters of a string are digits.
islower() This method checks if all the characters of a string are lowercase.
isupper() This method checks if all the characters of a string are uppercase.
isspace() This method checks if all the characters of a string are whitespaces.
join() This method joins all elements of an array of strings using a string as a separator.
lower() This method is used to convert all characters of a string to lowercase.
lstrip(char) This method is used to remove all the occurrences of a leading character from the string passed in the method. 
replace(old, new) This method replaces the current substring of a string with another substring.
rstrip() This method is used to remove all the occurrences of a trailing character from the string passed in the method. 
split() This method splits a string into a list of substrings using the separator passed as a parameter.
startswith() This method checks if the string starts with the specified substring.
strip() This method removes all the occurrences of the leading and trailing characters from a string.
title() This method capitalizes the first character of every word of the string.
upper() This method converts all the characters of a string to uppercase.
zfill(width) This method pads the string with zeros until it reaches the specified width.

String Manipulation Techniques

If you want to manipulate a string and transform its processing capabilities as needed, then Python allows you some techniques to manipulate a string:

 

Reverse a String

If you want to reverse a string then you can do that by following the method below:

Example:

# Create a string
Text = "Intellipaat"
print(Text[::-1]) # Output: taapilletnI

Split a String

If you want to extract all the words of a string in a list format, then you can do that by using the split() method.

Example: 

# Create a string
Text = "Learn With Intellipaat"

# Splitting the string
print(Text.split(" ")) # Output: ['Learn', 'With', 'Intellipaat']

Replacing Substrings

If you want to replace parts of a string with another substring, then you can do that by using the replace() method.

Example:

# Create a string
Text = "Learn With Intellipaat"

# Replacing a substring
print(Text.replace("Learn", "Grow")) # Output: Grow With Intellipaat

Changing Case

If you want to convert a string to uppercase, lowercase or some other format, then Python provides you with some methods to do the same.

Example: 

# Create a string
Text = "learn with intellipaat"

# Changing to uppercase
print(Text.upper()) # Output: LEARN WITH INTELLIPAAT

# Changing to lowercase
print(Text.lower()) # Output: learn with intellipaat

# Capitalizing the first character of every word
print(Text.title()) # Output: Learn With Intellipaat

# Capitalizing the first character only
print(Text.capitalize()) # Output: Learn with intellipaat


Stripping Characters

If you want to remove characters from the beginning or end of a string, then you can use some methods like strip(), lstrip(), or rstrip().

Example:

# Create a string
Text = "$$$Intellipaat$$$"

# Stripping all '$' characters from both ends
print(Text.strip("$")) # Output: Intellipaat

# Stripping '$' characters from the left
print(Text.lstrip("$")) # Output: Intellipaat$$$

# Stripping '$' characters from the right
print(Text.rstrip("$")) # Output: $$$Intellipaat

String Formatting

If you want to format a string by combining variables, expressions, or data values in a structured way to make it more readable and meaningful, Python provides multiple methods to do the same. Following are some of these methods:

 

  • Using ‘+’ Operator

By using this operator, you can easily concatenate two or more strings and variables.

# Create a string
Text = "Intellipaat"

# Concatenation of strings
print("Learn " + "With " + Text)
  • Using the % Operator

In this method, you can use a placeholder wherever you want to insert a string or a variable. Placeholders like %s(for strings), %d(for integers), and %f(for float) are used.

# Create a string
Text1 = "Intellipaat"
Text2 = "Python"
number = 1

# Concatenation of strings
print("%s provides No. %d %s Course" % (Text1, number, Text2))

# Output: Intellipaat provides No. 1 Python Course

Using format() Method

Similar to the % operator, the format() method works in the same way, but it is easier to work with and provides more flexibility to developers, as no placeholders are required here.

# Create a string
Text1 = "Intellipaat"
Text2 = "Python"
number = 1

# Concatenation of strings
print("{} provides No. {} {} Course".format(Text1, number, Text2))

# Output: Intellipaat provides No. 1 Python Course

 

  • Using f-strings

This is the most modern and efficient method of formatting strings. 

# Create a string
Text1 = "Intellipaat"
Text2 = "Python"
number = 1

# Concatenation of strings
print(f"{Text1} provides No. {Text2} {number} Course")

# Output: Intellipaat provides No. 1 Python Course

 

Slicing of Strings

slicing

If you want to extract a segment of a string, then you can do that by defining a range of indices. As you know, strings in Python are sequences of characters that start with index 0, then 1, and so on.

 

Example:

# Create a string
Text = "Intellipaat"

# Slicing of strings
sliced_text = Text[0:5]

# Printing the sliced string
print(sliced_text) # Output: Intel

The above example illustrates a simple slicing method. Following are some more methods to perform string slicing:

 

  • Omitting the Start or End Index

If the starting or ending index is not provided, then Python itself sets it to the lower and upper limit respectively.

 

Example:

# Create a string
Text = "Intellipaat"

# Slicing of strings
print(Text[:8]) # Output: Intellip
print(Text[4:]) # Output: llipaat

 

  • Using Step parameter

If you want to extract characters in an interval, then you can define the step as a parameter.

Example:

# Create a string
Text = "Intellipaat"

# Slicing of strings after an interval
print(Text[::2]) # Output: Itliat

 

  • Negative Slicing of Strings

If you pass a negative index as a parameter, then Python will count that index from the end.

Example:

# Create a string
Text = "Intellipaat"

# Negative Slicing of strings
print(Text[-5:]) # Output: ipaat

 

  • Reverse a String

If you pass -1 as a step parameter, then it will reverse the string.

Example:

# Create a string
Text = "Intellipaat"

# Reversing a string
print(Text[::-1]) # Output: taapilletnI

Get 100% Hike!

Master Most in Demand Skills Now!

Conclusion

Python provides a lot of methods and operators for string operations. These methods help developers in manipulating text data efficiently. With operations like slicing, formatting, and methods like join(), strip(), split(), and many more, you can process complex data easily.

If you want to explore more in this domain, you can enroll in Intellipaat’s Python Course and Give your career the right choice.

 

Our Python Courses Duration and Fees

Program Name
Start Date
Fees
Cohort starts on 14th Jan 2025
₹20,007

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.