Python Strings (with Example)

Strings in Python are used to define text component and are stored as a str data type. A Python string is a sequence of characters enclosed within the single-quote or double-quote notation.

  • Single-quote: 'hello'
  • Double-quote: "hello"

Print a Python String

To print a string in Python, pass the string as an argument of the print() function.


Assign a String to Variable

Use the equal operator (=) to assign a string to a Python variable.

Subscribe to my Newsletter

# String Assignment
var = 'hello'

Multiline Strings in Python

Multiline strings can be done with the single-quote or the double-quote notation. We need to triple the number of quotes in order to make multi-line strings.

# Use triple quotes to assign multiline
x = '''
I am 
# Can also use double-quotes
x = """
I am 

Nested Strings in Python

Nested strings in Python are string that contain the quote symbol (‘ or “) inside them.

Nested strings can happen when a quotation is encapsulated inside a string.

How to Double-Nest Strings in Python

In order to create nested strings in Python you need to use different quotation symbol for the quotation than the one used to define the string. (e.g. using single-quote inside the double-quote).

Although it is possible to use double-quotes inside single quotes, the standard is to use single-quotes inside double-quotes. The important is to be consistent.

# Nested Strings
x = """
My friend said: 
'hey, listen to me'

How to Triple-Nest Strings in Python

The preferred format for nested strings is to have double quotes > single quote > backtick with the backtick being the most nested and the double quote being the outer string assignment.

# Triple Nest
x = """
My friend said: 
'hey, listen to what this guy told me. He said:
`it is possible to triple-nest strings in Python!`.
What a dumb idea...'.
What a jerk!

Indexing of Strings

A string in Python is an Array.

An array in Python is when you can have multiple items in a single variable.

Thus, it is possible to select each item of the array (string) individually using its index.

Selecting First Letter of a String

Python is using zero-based indexing, so in order to select the first element, we are using 0 instead of 1.

# Selecting first letter of a string
x = 'python'

Selecting Last Letter of a String

To select the last letter of a string, we use the minus symbol.

# Selecting last letter of a string
x = 'python'

Looping Through a String in Python

For loops can be used to loop through any types of arrays, including strings.

# looping
for i in 'python':

Slicing Strings in Python

Slicing in Python is when you want to select a part of an array.

Get part of a String Using the Indexes

# Get part of string
x = 'Slice me like a cake'
# 4 is excluded

Slice a String from the Start

To slice a string until an index, use the colon notation up to an position. The position chosen is excluded.

In the example below, I am slicing from index 0 until the index 9, 9 excluded.

Adding no number before the colon is implied that you are starting from index 0.

# Slice from the start
x = 'Slice me like a cake'
Slice me 

Slice String from Index to the End

Similarly, adding no number after the colon makes it implicit that you want to slice until the end.

This time, the number 9 (index before the colon) is included.

# Slice from index to the end
x = 'Slice me like a cake'
like a cake

Negative Slicing of Strings

# Negative slicing
x = 'Slice me like a cake'
Slice me like a cak

Investigate Strings

Find How Long a String is in Python

# How long is a string
x = 'How long is this string'

How to Count Letters in a String

# String to variable
x = 'How long is this string'

# count the number of 's' in the string

Check if a String Contains Another String

# String to variable
x = 'How long is this string'

# Does the string contain the word "long"
if 'long' in x.lower():
    print('yes, it is') 
    print('no, it is not')

Change the Casing of Strings in Python

We can modify strings in many ways in Python. One of such ways is to modify casing of the string.

How to Convert a String to Uppercase

# Lower Case
x = 'Convert casing of this string'

# Uppercase
new_x = x.upper()


How to Convert a String to Lowercase

# Lower Case
x = 'Convert casing of this string'

# Lowercase
new_x = x.lower()

convert casing of this string

How to Convert a String to Titlecase

# Title Case
x = 'Convert casing of this string'

# Titlecase
new_x = x.title()

Convert Casing Of This String

Remove Whitespaces in Strings

Remove Spaces Before and After (Leading and Trailing)

The strip() method removes leading and trailing spaces in strings, but not the spaces between the words.

# Remove Spaces Before and after
x = '   Replace leading and trailing spaces from this string    '

Replace leading and trailing spaces from this string

Remove all Whitespaces in a String

The replace() method replaces any input string and replaces it with the output string that you give it.

# Remove all whitespaces
x = '   Replace whitespaces from this string    '

x.replace(' ', '')

Replacing Letters from Strings

Replace a Single Letter

# Replace the letter e
x = 'Replace the letter e'

x.replace('e', 'f')
Rfplacf thf lfttfr f

Replace first occurrence of a letter in string python

# Replace the letter e
x = 'Replace the letter e'

x.replace('e', 'f', 1)
Rfplace the letter e

Replace Letters Using a Dictionary

Example with a simple Password encryption.

# Replace letters
encrypt = {

x = 'password'

for k,v in encrypt.items():
    x = x.replace(k, v)


Decrypt Password

for k,v in encrypt.items():
    x = x.replace(v, k)


Splitting and Joining Strings in Python

Split a String in Python

The split() method allows you to split a string, using the character where you want to split the string as an argument.

# Split
x = 'hello, world'
splitx = x.split(',')
['hello', ' world']

Join a String in Python

The join() method can be used to join a list of items into a single string. The argument of the join() method is an array.

# Join
'hello, world'

Concatenate Strings in Python

Concatenating strings is the act of joining strings together. We have seen the join() method

Combine String Variables

# Combine string variables
x = 'Jean-Christophe'
y = 'Chouinard'

x + y

Add space in Concatenate

# Add space in Concatenate
x + ' ' + y
'Jean-Christophe Chouinard'

String %-Formatting

Python string formatting is used to format string.

It is originally done with the %-formatting operation. It is not recommended by Python docs as it has a number of errors. Use F-Strings instead.

That being said, here is how to use String %-formatting in Python.

name = 'JC'
"Hello, %s" % name
'Hello, JC'

The other problem of string formatting this way is that it is not as readable as F-strings.

name = 'JC'
last_name = 'Chouinard'
age = 32
born_in = 1990
"Hello, %s %s. You are %s years old, born in %s " % (name, last_name, age,born_in)

F-Strings in Python

F-Strings are a fantastic way to format strings.

They are readable and concise and allow you to perform calculations and even use methods inside strings.

Add variable to string

# Add variable to string
name = 'JC'
age = 12

s = f'Hello, I am {name} and I am {age}!'

Hello, I am JC and I am 12!

Counting Inside an F-String

# Count
name = 'JC'
age = 12

s = f'Hello, I am {name} and I am {age * 3}!'

Hello, I am JC and I am 36!

Applying Methods to an F-String

# Apply methods
name = 'JC'
age = 12

s = f'Hello, I am {name.lower()} and I am {age}!'

Hello, I am jc and I am 12!

Python Strings Methods

This is not an exhaustive list of Python methods, but a recollection of the most useful ones. The full list is available on w3Schools.

capitalize()Converts the first character to upper case
count()Count occurrences of a value in string
encode()Returns encoded version of a string
endswith()Returns True if string ends with a value
find()Returns position of a value if found in string
isalnum()Returns True if all characters in the string are alphanumeric
isalpha()Returns True if all characters in the string are in the alphabet
isnumeric()Returns True if all characters in the string are numeric
islower()Returns True if all characters in the string are lower case
join()Converts the elements of an iterable into a string
lower()Converts a string into lower case
replace('start','end')Returns a string where a specified value is replaced with a specified value
split()Splits the string at the specified separator, and returns a list
strip()Returns a trimmed version of the string
title()Converts the first character of each word to upper case
upper()Converts a string into upper case

This was a very simple introduction to Python strings, I strongly suggest that you dive deeper into F-Strings.

Enjoyed This Post?