Python Strings - The Definitive Guide

Learn to handle strings in Python.

Python Strings - The Definitive Guide

If you prefer to watch Youtube videos over reading blogs, check out our video on Python strings here.

Topics Covered

  1. What are strings in Python?
  2. Accessing characters in a Python string
  3. String Slicing
  4. How to replace characters in a string in Python?
  5. Concatenating strings in Python
  6. Iterating through a string in Python
  7. Check if a Substring is Present in a Given String in Python
  8. Escape sequences in Python String

What are strings in Python?

Strings are amongst the most popular data types in Python. A string can be defined as a sequence of characters.

How to create strings in Python?

Strings can be created by enclosing characters inside a single quote, double-quotes, and triple quotes.

Code

# Single Quotes
my_string = 'Pylenin'
print(my_string)

# Double Quotes
my_string = "Pylenin"
print(my_string)

# Triple Quotes
# can be extended over multiple lines
my_string = """Check out Pylenin
               for Python related blogs and videos"""
print(my_string)

Output

Pylenin
Pylenin
Check out Pylenin
               for Python related blogs and videos

As you can see in the code above, we are assigning a string to a variable. It is done with the variable name followed by an equal sign and the string.

Unless necessary, try not to use triple quotes for strings. It is generally used for writing docstrings in your Python code, which acts like a documentation.

How to access characters in a Python string?

You can access individual characters of a string through string indexing and a range of characters using slicing.

In Python, the index starts from 0 and keeps increasing by 1 with every character. This is called Positive Indexing (or indexing from the beginning). If there are n characters in a string, the 1st character will be index 0 and the last character will have index n-1.

Let’s look at the image below for a better understanding.

Positive Indexing in Python

Python also allows negative indexing(indexing from the end). If there are n characters in a string, the last character will have an index of -1 and the first character will have an index of -n.

Let’s look at the image below for a better understanding.

Negative Indexing in Python

Code

str = 'PYLENIN'

# first character
print('str[0] =', str[0])

# last character
print('str[-1] =', str[-1])

# second character
print('str[1] =', str[1])

# second last character
print('str[-2] =', str[-2])

Output

str[0] = P
str[-1] = N
str[1] = Y
str[-2] = I

If you try to access a character out of range, it will raise an IndexError.

Also, the index must be an integer. You can’t use floats or other types for indexing. This will result in TypeError.

Code/Output

str = 'PYLENIN'

print(str[10])
>>> IndexError: string index out of range

print(str[1.5])
>>> TypeError: string indices must be integers

String Slicing

To access a range of characters, you need to use slicing. Basically, you have to specify the start index and the end index, separated by a colon, to return a part of the string.

Remember - The last index is not included.

Let's say you want to access all the elements from the 2nd index to the 4th index of PYLENIN string. In that case, your end index will be 5.

Code

str = 'PYLENIN'

# 2nd to 4th index
print('str[2:5] =', str[2:5])

Output

str[2:5] = LEN
String slicing in Python

If you leave out the start index, the range will start at the first character. This is the same as mentioning the start index as 0.

Code

str = 'PYLENIN'

# 2nd to 4th index
print('str[:5] =', str[:5])

Output

str[:5] = PYLEN
String slicing without the start index

If you leave out the end index, the range will go to the end.

Code

str = 'PYLENIN'

# 2nd to 4th index
print('str[2:] =', str[2:])

Output

str[2:] = LENIN
String slicing without the last index

Check out the code below. Both the statements produce the same result.

Code

str = 'PYLENIN'

print('str[2:5] =', str[2:5])
print('str[-5:-2] =', str[-5:-2])

Output

str[2:5] = LEN
str[-5:-2] = LEN

How to replace characters in a string in Python?

Can you replace characters in a string in Python?

In Python, strings are immutable.

This means elements of a string cannot be changed or replaced once they have been assigned.

Code

x = "Pylenin"
x[0] = "L"

Output

Traceback (most recent call last):
  File "file_location", line 2, in <module>
    x[0] = "L"
TypeError: 'str' object does not support item assignment

However, we can certainly create a copy of our string with our necessary replacements.

Method 1 - Python string replace() method

The replace() method replaces a specified character/phrase with another.

Syntax of replace()

string.replace(oldstring, newstring, count)

oldstring - The string to replace(required)
newstring - The string to replace with(required)
count - A number specifying how many occurrences 
        of the old value you want to replace. 
        Default is all occurrences (optional)
Example 1

Replace all occurrences of the word Pylenin.

Code

txt = "I like Pylenin"

x = txt.replace("Pylenin", "Python")

print(x)

Output

I like Python
Example 2

Replace the first two occurrences of the word Python.

Code

txt = "Python is the best. " \
      "I love Python. " \
      "I enjoy Python"

x = txt.replace("Python", "Pylenin", 2)

print(x)

Output

Pylenin is the best. I love Pylenin. I enjoy Python

Method 2 - Python list() method

Another solution would be to convert a string to a python list and then make necessary changes. Unlike Python strings, Python lists are mutable.

Code

old_str = "foofoo"

str_list = list(old_str)
str_list[0] = 'd'
new_string = "".join(str_list)

print(new_string)

Output

doofoo

Concatenating strings in Python

Concatenation is the process of joining of two or more strings into a single string.

In Python, the + operator is used for concatenation. You can also concatenate two strings by writing them together. Another way is to use the * operator to repeat the string for a given number of times.

Code

str1 = "I like "
str2 = "Pylenin"

print(str1+str2)

print(str1, str2)

print(str1*2)

Output

I like Pylenin
I like  Pylenin
I like I like 

How to iterate through a string in Python?

We can iterate or loop through a string in Python by using the for loop.

Code

str1 = "Pylenin"

for letter in str1:
    print(letter)

Output

P
y
l
e
n
i
n

Check if a Substring is Present in a Given String in Python

Given two strings, check if s1 is present in s2.

Method 1 - Using in and not in keywords

Code

s2 = "I like Pylenin"
s1 = 'like'

print(s1 in s2)
print(s1 not in s2)

Output

True
False

Method 2 - Python String find() Method

The find() method in Python finds the first occurrence of a specified value in a given string. It returns the index where the substring s1 occurs. It returns -1 if the value is not found.

The find() method is similar to the index() method. Only difference - index() method raises an exception if the value is not found.

Code

s2 = "I like Pylenin"
s1 = 'like'

print(s2.find(s1))

Output

2

The above result tells us that the like substring first occurs at the 2nd index.

Let’s check for another substring.

Code

s2 = "I like Pylenin"
s1 = 'Python'

print(s2.find(s1))

Output

-1

The above result tells us that the substring Python doesn’t exist in s1.

Method 3 - Python String count() Method

The count() method returns the number of times a substring s1 appears in the string s2. It is not case-sensitive.

Syntax

string.count(value, start, end)

value:	The substring to search for(required)
start:	The integer position to start the search. Default is 0.(Optional)
end:	The integer position to end the search. Default is the end of the string.(Optional)

Code

s2 = "I like Pylenin"
s1 = 'like'

if s2.count(s1) > 0:
    print(f"'{s1}' exists in '{s2}'")

Output

'like' exists in 'I like Pylenin'

Let’s search for a non-existing string.

Code

s2 = "I like Pylenin"
s1 = 'Python'

if s2.count(s1) > 0:
    print(f"'{s1}' exists in '{s2}'")
else:
    print(f"'{s1}' doesn't exist in '{s2}'")

Output

'Python' doesn't exist in 'I like Pylenin'

Let’s now search a substring s1 in a specific portion of string s2.

Code

s2 = "I like reading Pylenin blogs on Python"
s1 = 'Python'

# Search between position 10 and 20
if s2.count(s1, 10, 20) > 0:
    print(f"'{s1}' exists in '{s2}'")
else:
    print(f"'{s1}' doesn't exist in '{s2}'")

print(s2.find(s1))

Output

'Python' doesn't exist in 'I like reading Pylenin blogs on Python'
32

As you can see, the substring Python doesn’t occur between positions 10 and 20. The find() method shows that it occurs at position 32.


Escape sequences in Python String

Escape sequences or Escape characters in Python, are used to insert characters that are illegal in a string.

Here is an example of an illegal character in a Python string.

Example1 - "Pylenin said, "Hi there""
Example2 - 'Pylenin said, 'Hi there''

In Example 1, we have double quotes inside double quotes. In Example 2, we have single quotes inside of single quotes. These qualify as illegal characters in a string.

If we try to print it, Python will throw us a SyntaxError.

One way to fix this is by using Escape characters or sequences.

If we are using single quotes to represent a string, all the single quotes inside the string must be escaped with a \ character.

Similarly, if we are using double quotes to represent a string, all the double quotes inside the string must be escaped with a \ character. .

Code

str1 = "Pylenin said, \"Hi there\""
print(str1)

str2 = 'Pylenin said, \'Hi there\''
print(str2)

Output

Pylenin said, "Hi there"
Pylenin said, 'Hi there'

Other Escape Sequences in Python

Escape Sequence Description
\newline Backslash and newline ignored
\ Backlash
' Single Quote
" Double Quote
\a ASCII Bell
\b ASCII Backspace
\f ASCII Formfeed
\n ASCII Linefeed
\r ASCII Carriage Return
\t ASCII Horizontal Tab
\v ASCII Vertical Tab
\ooo Character with octal value ooo
\xHH Character with hexadecimal value HH

Hope you enjoyed this article on Python Strings. In case of any doubts or suggestions, connect with me on Twitter.

String Formatting in Python - The Definite Guide
Learn different ways to format strings in Python and test for the fastest method.

Subscribe to Pylenin

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe