The Python String type contains a sequence (String) of characters. To work with text or character data in Python, we use Strings. Once a Python String is created, we can do a lot of operations on it, and We can search inside it, create a substring from it, split it, find if specific characters present in it, replace few characters of a string, Plus many other things. This Definitive guide on Python String will cover every topic related to String. At the end of this guide, I recommend you to solve the String Exercise and Quiz to improve your string skills
The Python String type contains a sequence (String) of characters. To work with text or character data in Python, we use Strings. Once a Python String is created, we can do a lot of operations on it, and We can search inside it, create a substring from it, split it, find if specific characters present in it, replace few characters of a string, Plus many other things. This Definitive guide on Python String will cover every topic related to String. At the end of this guide, I recommend you to solve the String Exercise and Quiz to improve your string skills
String literal
A string literal in Python is a sequence of characters enclosed within a single quote or double quote. These characters could be anything like letters, numbers, or special symbols which are enclosed within two quotation marks. For example, "PYnative"
is a string literal. Let’s display this string literal using the print()
function. print("PYnative")
You can also assign a string literal to a variable so you can manipulate string as when required.
myString = "PYnative"
print(myString)
Here, myString
is a variable referring to string literal "PYnative"
2 ways to Create a String in Python
By String literal: Python String literal is created by using single, double-quotes, Triple quotes. Below are the all valid ways to create a string by string literal.
print("Creating a String with single Quotes")
string1 = 'My first String'
print(string1)
print("Creating a String with double Quotes")
string2 = "My second String"
print(string2)
print("Creating a String with triple Quotes")
string3 = '''My third String'''
print(string3)
print("Creating a String with triple Quotes")
string4 = """My fourth String"""
print(string4)
Output:
Creating a String with single Quotes My first String Creating a String with double Quotes My second String Creating a String with triple Quotes My third String Creating a String with triple Quotes My fourth String
By str() class: Python String is created by using the built-in type str
. it returns a string version of an object. If the object is not provided, returns the empty string.
string5 = str("My fifth String") print(string5)
Here Python will create a reference variable string5
to refer to the object "My fifth String"
Add image
Common String operation
As we know, we can do a lot with Python String. Let’s see the commonly used string operation in Python
Iterating Through String
Let’s see the easiest way to iterate through each character in a string in Python Add description
sampleString = "James Bond" print("Iterating through string to Print each character ") for i in sampleString: print(i)
Output:
Iterating through string to Print each character J a m e s B o n d
Note: Python does not have a character or char type. If you create a variable that holds a single character, it will be treated as a string of length 1. For example var1 = 'a'
is string of length 1.
Finding String Length
Many times we need the size or length of a string to perform various operations. We can use string function len()
to get the length of the string.
str5 = "PYnative" string_length = len(str5) print(string_length)
Output: 8
String membership test
Many times while writing code, we encounter a situation where we need to check if a specific character or phrase is present in the string or not, we call it a string membership test. Example to check if a given character is part of a String
sampelStr = "PYnative" flag = 't' in sampleStr print(flag) flag = 'T' in sampleStr print(flag)
Output:
True False
Note: String membership test is case sensitive Example to check if a given substring is part of a String
sampleStr = "I'm gonna make him an offer he can't refuse" flag = "offer" in sampleStr print(flag) flag = "offers" in sampleStr print(flag)
Output:
True False
String Indexing and Slicing
As you know, the string is a sequence data type. It can be accessed through indexing and slicing. This section will guide you through accessing string through index number, slice them to get character sequence or substring.
- Using indexing, we can access individual characters from a string.
- Using slicing, we can access a range of characters from the string
String indexing
For example, You want to access the first character or character present in the fifth position. Each of a string’s characters corresponds to an index number, starting with the index number 0. The first character is present at index 0, and the last character is present at index string length – 1. The following diagram will help you to understand the string indexing concept. Access the first character of the string
name = "The Joker" print(name[0])
Output: T
Access the last character of the string
name = "The Joker" print(name[len(name) - 1])
Output: r
Access the fifth character of the string
name = "The Joker" print(name[4])
Output: J
Note: To get the fifth character, we passed 4 as an index number because the index starts from 0. Access Characters by Negative Index Number. A string can be access using both positive and negative index number. Add Image
- When we access a string using positive index number Python starts searching a character from the beginning of a string.
- When we access a string using negative index number Python starts searching a character from the end of a string.
Access the last character of the string by negative index number
name = "The Joker" print(name[-1])
Output: r
Access second last character from a string
name = "The Joker" print(name[-2])
Output: e
String Slicing
Slicing is nothing but a character sequence or substring of an original string. For example, name = "The Joker"
, and I want to access substring Joke
, in such cases, we use a technique called string slicing. For example, get a substring from index 4 to 8.
name = "The Joker" string_slice = name[4:8] print(string_slice)
Slicing Syntax: str[start_index : end_index : step]
- The
start_index
andstep
parameters are optional. - The
step
argument in a slice is the steps to take from the start to end index.
name = "The Joker" string_slice = name[2:8:2] print(string_slice)
Output: eJk
. As you can see the substring contains characters from indexes 2, 4 and 6. Add image here
Using Negative numbers in Slice.
A string can be sliced using both positive and negative position numbers. When we use a negative number in the start or end position, Python starts getting substring from the end of a string.
name = "The Joker" sampleStr = name[-5:-3] print(sampleStr)
Output: Jo
Add image here
Various examples of string slicing
Accessing entire string using slicing
name = "The Joker" print(name[:]) print(name[::])
Output:
The Joker The Joker
Access the first three characters
name = "The Joker" first_three_chars = name[:3] print(first_three_chars)
Output: The
Reverse a String using Slicing
name = "The Joker" reverse_name = name[::-1] print(reverse_name)
Output: rekoJ ehT
String Concatenation
String concatenation means add strings together. There are multiple ways to concatenate strings in a Python, The best and quickest way of appending a string to a string variable is to use +
or +=
operator. String Concatenation using + Operator
str1 = 'James' str2 = 'Bond' print("Concatenated Strings using + operator") str3 = str1 + str2 print(str3) print("Add one string to another using += operator") str1 +=str2 print(str1)
Output:
Concatenated Strings using + operator JamesBond Add one string to another using += operator JamesBond
Now Let’s see the other ways to concatenate strings in Python Using % operator to contact strings Most commonly, the %
operator is used to format string. When we want to combine strings along with some formatting, we can use %
operator. Let’s see how to format and concatenate strings adding -
in between using the %
operator.
str1 = "Guido" str2 = "van" str3 = "Rossum" print("%s-%s-%s" % (str1, str2, str3))
Output: Guido-van-Rossum
Using format() function to contact strings To format string, we use str.format()
. Also, this method allows us to concatenate and format strings. Using the format()
function, we can provide positional and keyword parameters.
- Use the positional parameters, to specify in which format you want to concatenate strings.
- Use keyword parameters to specify string orders.
str1 = "Guido" str2 = "van" str3 = "Rossum" print("%s-%s-%s" % (str1, str2, str3)) str4 = "{}*{}*{}".format(str1, str2, str3) print(str4)
Output: Guido*van*Rossum
using str.join()
method If you have a list of strings and you want to combine all string into one, then you should use join()
method.
strList = ["Jon", "Joe", "Emma", "Eric"] print("Join Strings using Separator #") sampleStr = "#".join(strList) print(sampleStr) print("Join Strings without Separator") sampleStr = "".join(strList) print(sampleStr)
Output:
Join Strings using Separator # Jon#Joe#Emma#Eric Join Strings without Separator JonJoeEmmaEric
String Methods
Below is the list of the string methods available in Python. I have explained the use of each method in brief. Note, every string method returns a new string, They do not change the original string.
capitalize()
The capitalize()
method converts the first character of a string to uppercase and lowercases all other characters.
sampleStr = "hope is a good thing" # String before using capitalize() method" print(sampleStr) newStr = sampleStr.capitalize() # String after using capitalize() method" print(newStr)
Output:
hope is a good thing Hope is a good thing
casefold()
The casefold()
converts string into lower case. casefold()
is an aggressive lower()
method. The major advantage of using a casefold()
method over the lower()
method is when you’re using non-English characters. casefold()
will convert even the caseless letters. The casefold()
is used to make many of the more unique Unicode characters more comparable. It is another form of normalizing text that may initially appear to be very different, but it takes characters of many different languages into account. If you want to know the difference between lower()
vs. casefold()
, please read this StackOverflow answer.
sampleStr = "Hope Is a Good Thing" # String before using casefold() method" print(sampleStr) newStr = sampleStr.casefold() # String after using casefold() method" print(newStr)
Output:
Hope Is a Good Thing hope is a good thing
Second Example:
germanString = "Müller Weiß" # German letters after using lower() method" lowerCaseString = germanString.lower() print(lowerCaseString) # German letters after using casefold() method" caseFoldString = germanString.casefold() print(caseFoldString)
Output:
müller weiß müller weiss
center()
As the name suggests, The center()
method is used to get the centered align string. The fill character fills the left and right space. If fill character is not specified space is used.
name = "Maximus" # String before using center() method" print(name) # String after using center() method" newName = name.center(40) print(newName) # String after using center() method with fill character" newName = name.center(40, "*") print(newName)
Output:
Maximus Maximus ****************Maximus*****************
count()
Use the count()
method to count how many times a particle character appeared in a string.
str5 = "Banana" # count the occurrence of character 'a' in given string aCount = str5.count('a') print("Letter a appeared", aCount, "times") str6 = "Emma knows ML. Emma works at Google" # count the occurrence of phrase 'Emma' in given string phraseCount = str6.count('Emma') print("Emma appeared ", phraseCount, "times")
Output:
Letter a appeared 3 times Emma appeared 2 times
Count occurrence of a value within a range (search withing a given start and stop index number)
# count the appearance of phrase 'Emma' from index 5 to the end of a string str6 = "Emma knows ML. Emma works at Google, Emma knows Django " phraseCount = str6.count('Emma', 5) print("Emma appeared ", phraseCount, "times") # count the appearance of phrase 'Emma' from index 5 to 20 phraseCount = str6.count('Emma', 5, 20) print("Emma appeared ", phraseCount, "times")
Output:
Emma appeared 2 times Emma appeared 1 times
encode()
We use this method when we need to convert any string into a different encoding format. If you want to convert Unicode strings into any encodings supported by Python, use the string’s encode()
method. By default, Python uses utf-8
encoding while creating a string. This method accepts the following two parameters.
- encoding: The encoding type into which you want to encode a string.
- errors: What to do if you encountered any errors in this process. It provides us the six types of an error response that we can use to analyze the problem
germanString = "Müller Weiß" # print string print('The string is:', germanString) # ASCII encoded version of a string with errors='strict' utfString = germanString.encode("utf-8", 'strict') print("UTF-8 encoded String is", utfString)
Output:
output
The string is: Müller Weiß UTF-8 encoded String is b'M\xc3\xbcller Wei\xc3\x9f'
endswith()
As the name suggests, Use endswith()
method when you want to check whether a string ends with a specific character or phrase.
str7 = "Joe is system developer" print("The string is:", str7) flag = str7.endswith("developer") print("The string endswith phrase'developer' ", flag)
Output:
The string is: Joe is system developer The string endswith phrase'developer' True
Check string ends with a specific character or phrase within a range (search withing a given start and stop index number). Also, using this method, you can check substring of the original string ends with a specific character or phrase
str7 = "Joe is Software Engineer" print("The string is:", str7) flag = str7.endswith("is", 3, 6) print("The sub string endswith phrase 'is' ", flag)
Output:
The string is: Joe is Software Engineer The sub string endswith phrase 'is' True
expandtabs()
Do you want to specify the tab size for your string then use the expandtabs()
method. Tab size is nothing but the number of whitespaces between each character of the string). Default tab size is 8
sampleStr = "A\tp\tp\tl\te" print("The String with default tab size") print(sampleStr) print("String after setting Expand tab size to 2") print(sampleStr.expandtabs(2))
Output:
The String with default tab size A p p l e String after setting Expand tab size to 2 A p p l e
find()
Use the find()
method to find the position of a given phrase or substring within the string. The find()
method searches the string for a specified value and returns the position where it was found first. If the specified value is not found, it returns -1.
sampleStr = "My name is Maximus" print("The String is:", sampleStr) index = sampleStr.find("name") print("'name' phrase found at index", index)
Output:
The String is: My name is Maximus 'name' phrase found at index 3
Find the index of phrase or value within a range. Search string from the given start and stop index number to finding the position of a specified value. People use this technique to get the first index of a phrase within a substring of the original.
sampleStr = "You have a great name" print("The String is:", sampleStr) print("Find position of 'eat' in substring", sampleStr[10:16]) index = sampleStr.find("eat", 10, 16) print("'eat' phrase found at index", index)
Output:
Find postion of 'eat' in substring great 'eat' phrase found at index 13
More to cover we will cover after some time
String Modification
When we work with any strings, It is undeniable we need to manipulate it for various needs. When we say string modification, it can be adding new characters or phrases into a string, and removing/replacing characters or phrases from a string. Update a character of a string. Let’s see how to update the 5th character of a string. Update string by removing some characters from it Update string by adding new characters into it Update string by replacing a few characters/phrases from it Note: Cover other ways in next section
- Assign String to variable
- 5 ways to create a string
- Multiline String
- String slicing(Accessing characters from String in Python)
- Common String operation(Concatenation, Iterating Through String, String Membership Test)
- String functions
- Negative indexing
- String concatenation
- String formatting*
- Escape Character
- String immutability(Deleting/Updating from a String)
- Update string character
- Update Entire String
- Deletion of a character
- Delete entire string
- String constants
- Python String Operations
- Programs of Python Strings
- Built-in functions to Work with Python
- Raw String to ignore escape sequence
- Custom String Formatting
- Template strings
- String Special Operators
- String Formatting Operator
- Unicode String
- String %
This quiz is automatically created to help you get started. It will be created only once.