Python String

Summary: in this tutorial, you will learn about Python string, string’s features and string operations.

Introduction to Python string

Python string is one of the most popular types in Python. By definition, a string is a sequence of characters. You can create a string simply by enclosing characters in single or double quotes. If a string spans multiple lines, you can use triple single or double quotes to enclose characters.

Let’s look at the following example:

In this example, we defined four strings.

Notice that a string must begins and ends with the same type of quotes.

Python string features

Python string object has the following features:

  • String is scalar type, meaning that the Python interpreter treats string as a single value not a container that holds other Python objects.
  • String is immutable, for efficiency reason. It means string is not modifiable. If you change an element inside a string, a new string is created.
  • String consists of individual characters so you can access sequentially using slicing.

Accessing string elements

Because a string is a sequence of character, you can access its elements using index or slice notation.  The following example demonstrates accessing elements using index and slice notation:

In this example, we defined a string s. Then we accessed element of string s via index using square [] brackets: s[0] and s[-1]. If you use negative index, Python will count from the end of string starting -1, -2 and so forth. We also accessed a substring of s using slice notation s[0:6].

Python String Index

Because string is immutable, the following assignment will issue an error:

So how do you update a string?

Updating a string

Update a string requires creating a new string. You can “update” an existing string by assigning or reassigning a new string to the old one. A new string may or may not relate to the old one. Take a look at the following example:

In this example, we assigned substring of s to new string variables s1 and s2. We also assigned string s to its substring. It is important to note that s is pointing to a new string not the old one.

Python string operators

You can apply many operators on strings.  The following example demonstrates how to use operators on strings:

The in and not in operators

The  in and  not in operators allow you to check if a string appears in another string. See the following example:

Python string concatenating operator +

You can use operator  + to create a new string from existing ones. The following example demonstrates the string concatenation:

It is not recommended to use operator + for string concatenation because of the performance. Each time you use operator +, Python has to allocate memory for all string involved, including the result string.

Python string built-in methods

The following table illustrates the most important string’s built-in methods:

MethodDescription
string.capitalize()Converts the first character of a string into uppercase.
string.center(width)Center justifies the original string into a given width size, padded with space for the rest.
string.count(str, beg=0, end=len(string))Returns number of times that str occurs in string with index starts at begs position and ends at end position. The default value of end position is the last position of the string. The default value of the beg position is the first position of the string.
string.endswith(str, beg=0, end=len(string))Check the end of a string for a match
string.expandtabs(tabsize=8)Convert all tabs in string to multiple spaces, if tabsize is not passed, default to 8 spaces per tab.
string.find(str, b=0 e=len(string))Checks if str appears in string or in substring of string specified by starting index b and ending index e. Return position of the first character of the first instance of string str in string, otherwise return -1 if str not found in string.
string.format(*args, **kwargs)Format string based on given input parameters
string.index(str, b=0, e=len(string))Similar to find(), but throw an exception if str not found
string.isalnum()Returns True if string contains only alphabetic and/or numeric characters and string has at least 1 character, otherwise return False
string.isalpha()Returns True if string has at least 1 character and all characters are alphabetic, and otherwise returns False
string.isdecimal()Returns True if string has only decimal digits, and otherwise returns False
string.isdigit()Returns True if string has only digits, and otherwise returns False
string.islower()Returns True if at least 1 cased character exists and all characters in string are in lowercase, otherwise returns False
string.isnumeric()Returns True if string has only numeric characters, otherwise returns False
string.isspace()Returns True if string contains only whitespace characters, and otherwise returns False
string.istitle()Returns True if the first character of each word in a string are in uppercase, otherwise returns False.
string.isupper()Returns True if at least 1 cased character exists and all characters in string are in uppercase, otherwise returns False
string.join()Concatenate a list of string to form a single string with the original string between each element.
string.ljust(width)Left justifies the original string into a given width size, padded with space for the rest.
string.lower()Converts all characters in the string into lowercase.
string.lstrip()Returns original string except any whitespace at the beginning of the string has been removed
string.replace(str1, str2, num=string.count(str1))Replaces num occurrences of str1 in string with str2. If num is not passed, replace all occurrences.
string.rfind(str, beg=0, end=len(string))Similar to find(), but its search starts from the end of the string
string.rindex( str, b=0, e=len(string))Similar to index(), but its search starts from the end of the string
string.rjust(width)Right justifies the original string into a given width size, padded with space for the rest.
string.rstrip()Returns the original string except any whitespace at the end of string has been removed
string.split(str="", num=string.count(str))returns a list of substrings in the string
string.splitlines( num=string.count('\n'))Returns a list of single line strings from the original multiple line string.
string.startswith(str, b=0, e=len(string))Check the beginning of a string for a match
string.strip([obj])Returns original string except any whitespace at the beginning or end of the string has been removed
string.swapcase()For all characters of string, convert uppercase to lowercase and vice versa.
string.title()Capitalizes the first character of each word in a string
string.upper()Converts all characters of a string into uppercase.
  • Was this tutorial helpful ?
  • YesNo