Python Strings: The Complete Guide

Python String is a built-in data type representing the arrays of bytes representing the Unicode characters. Python does not have the character data type, and a single character is simply a string with a length of 1.

Creating a string

To create a string, use “single quotes(”),” or “double quotes(“”)”, or even triple quotes(”’ ”’).

print("Millie Bobby Brown")
print('Millie Bobby Brown')
print('''Millie Bobby Brown''')

Output

Millie Bobby Brown
Millie Bobby Brown
Millie Bobby Brown

We can display the String literal with the print() function.

We used single, double, and triple quotes in the above example. We will get the same output, but the triple quote is helpful when we have double-quoted words as a string.

print('''Mill's ''')

Output

Mill's

Accessing characters in a string

To access the characters of a string, you can use an “index” like array. For example, individual characters of the String can be accessed by using a method of Indexing. The slicing method is used to access the range of characters in the String.

Slicing in the String is done using the Slicing operator (colon). Indexing allows negative address references to access the characters from the back of a String, e.g., -1 refers to the last character, -2 refers to a second last character, and so on.

While accessing the index out of the range will cause the IndexError. Additionally, only Integer datatypes can be passed as the index, float, or other types will cause a TypeError.

StrA = "MillieBobbyBrown"

print("Initial String: ", StrA)
print("\nFirst character of String is: ", StrA[0])
print("\nLast character of String is: ", StrA[-1])
print("\nSlicing characters from 3-12: ", StrA[3:12])
print("\nSlicing characters between " + "3rd and 2nd last character: ", StrA[0:-5])

Output

Initial String: MillieBobbyBrown

First character of String is: M

Last character of String is: n

Slicing characters from 3-12: lieBobbyB

Slicing characters between 3rd and 2nd last character: MillieBobby

Deleting characters from a string

In Python, updation or deleting the characters from the String is prohibited. It will cause an error because item assignment or item deletion from the String is not supported.

Although deletion of the entire String is possible with the built-in del keyword, it is because Strings are immutable. Hence elements of the String cannot be changed once assigned.

StrA = "MillieBobbyBrown"
print("Initial String: ") 
print(StrA)

StrA[2] = 'K'
print("\nUpdating character at 2nd Index: ") 
print(StrA)

Output

TypeError: 'str' object does not support item assignment

Deleting an entire string

To delete an entire string in Python, you can use the “del” keyword.

StrA = "MillieBobbyBrown"
print("Initial String: ") 
print(StrA)

del StrA
print(StrA)

Output

Initial String:
MillieBobbyBrown

NameError: name 'StrA' is not defined

After we removed the StrA, it now says that StrA is not defined.

String slicing

Slicing in a String uses a Slicing operator (colon).

# Creating a String
String1 = "AppDividend"
print("Initial String: ")
print(String1)

# Printing 3rd to 12th character
print("\nSlicing characters from 2-10: ")
print(String1[2:10])

Output

Initial String:
AppDividend

Slicing characters from 2-10:
pDividen

Escape Sequencing

Escape sequences start with a backslash and can be interpreted differently. If single quotes represent a string, then all the single quotes in the String must be escaped, and the same is done for Double Quotes.

str_1 = '''ping's "world"'''
print("String with use of Triple Quotes: ")
print(str_1)
 
# Escaping Single Quote
str_1 = 'ping\'s "world"'
print("\nEscaping Single Quote: ")
print(str_1)
 
# Escaping Double Quotes
str_1 = "ping's \"world\""
print("\nEscaping Double Quotes: ")
print(str_1)

Output

String with use of Triple Quotes:
ping's "world"

Escaping Single Quote:
ping's "world"

Escaping Double Quotes:
ping's "world"

Formatting of Strings

Strings in Python can be formatted using the format() method, a versatile and powerful tool.

str_1 = "{} {} to the {}".format('Hello', 'World', 'DB')

print(str_1)

Output

Hello World to the DB

Python string methods

Method Name Definition
Python String partition() It is used to split the String at the first occurrence of the separator. It returns a tuple containing the part before the separator, the separator, and the part after the separator.
Python String istitle() It returns True if all words in a text start with an upper case letter, and the rest are lower case letters; otherwise, False.
Python String isprintable() It returns True if all the characters are printable; otherwise, False.
Python String isidentifier() It returns True if the String is a valid identifier. Otherwise False.
Python String title() It returns a string where the upper case is the first character in every word”. Like a header or a title.
Python String expandtabs() It is used to set the tab size to the specified number of whitespace.
Python String zfill() It is used to add zeros (0) at the beginning of the String until it reaches the specified length.
Python String rsplit() It is used to split a string into a list, starting from the right by the separator as a delimiter.
Python String rfind() It returns the highest index of the substring (if found). If not found, it returns -1.
Python String swapcase() It is used to convert all the characters to their opposite letter case(uppercase to lowercase and vice versa) and returns the String.
Python String casefold() It is used to convert all characters of the String into lowercase letters and returns a new string.
Python String index() It is used to find the first occurrence of the specified value.
Python String isspace() It returns True if all the characters in a string are whitespaces, otherwise False.
Python String maketrans() It returns a mapping table for translation usable for the translate() method.
Python String isdecimal() It returns True if all characters in a string are decimal characters. If not, it returns False.
Python String find() It is used to find the first occurrence of the specified value.
Python String startswith() It returns True if a string starts with the specified prefix(String). If not, it returns False.

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.