Python Strings – Get ready to work with sequence of characters

In this article, we will talk about Python strings.

They are like character arrays in C++.

We will learn how to declare, index, slice, format and delete them and learn about some in-built methods and functions on strings.

Keeping you updated with latest technology trends, Join TechVidvan on Telegram

What are Strings in Python?

Python does not have arrays like C++ or Java. It has lists and strings.

Lists are collections of values and are mutable.

Strings are sequences of characters and are immutable.

Let’s start with an example.

‘Drag me to hell’. This is a string, we surround it in single quotes here.

Declaring Python String

1. String literals in Python

String literals are surrounded by single quotes or double-quotes.

‘Drag me to hell’

“Drag me to hell”

You can also surround them with triple quotes (groups of 3 single quotes or double quotes).

“””Drag me to hell”””
”’Drag me to hell”’

Or using backslashes.

>> ‘Hello\
How are you?’
‘HelloHow are you?’

You cannot start a string with a single quote and end it with a double quote (and vice versa).

But if you surround a string with single quotes and also want to use single quotes as part of the string, you have to escape it with a backslash (\).

‘Drag madam\’s son to hell’

This statement causes a SyntaxError:

‘Drag madam’s son to hell’

You can also do this with double-quotes.

If you want to ignore escape sequences, you can create a raw string by using an ‘r’ or ‘R’ prefix with the string.

Common escape sequences:

  • \\ Backslash
  • \’ Single quotes
  • \” Double quotes
  • \n Linefeed
  • \t Horizontal tab

We can assign a string to a variable.


You can also create a string with the str() function.

>>> str(123)


>>> str('Hi')



Indexing Strings in Python

We can access a single character in a string through indexing it.

For this, we use square brackets and an index or the position of that character in the string.

Indexing starts at 0, not 1.python string indexing

1. Positive Indexing in Python

If we perform indexing left to right in the above python string, we have the indices 0 to 19.

We have 20 characters.

Even the space and exclamation mark are characters.

So to access the letter b, we can type this:

>>> text[7]


>>> text[21]


Traceback (most recent call last):
  File “<pyshell#65>”, line 1, in <module>
IndexError: string index out of range

2. Negative Indexing in Python

Negative indexing happens right to left in the python string.

The index -1 has the last character in the string and keep increasing the index in negative for characters in the left.

To get the letter ‘b’, we will use the -13 index.




Slicing Strings in Python

We can get parts of strings at one time by slicing it with the slicing operator [:].

Let us see how to do this.

>>> text[2:7]


‘ushi ‘

[2:7] is a slice that gives us the characters from index 2 to index 6, index 7 is not included.

The following are different slices for this string:

>>> text[:] #complete string
'Ayushi bought a pen!'
>>> text[:7] #beginning to index 6
'Ayushi '
>>> text[3:] #index 3 to end
'shi bought a pen!'
>>> text[-2:-7] #-2 to -7 left to right is nothing
>>> text[-7:-2] #index -7 to -1 left to right
' a pe'

We can also include the number of steps it should take while traversing.

>>> text[::2]
'Auh ogtapn'
>>> text[2:13:2]
'uh ogt'

In the above Python strings examples, it skips one character every time.

Deleting/Updating Strings in Python

Strings are immutable and you cannot delete them or update them.

You can assign a new object to the variable:

>>> work='RA'
>>> work='SRA'

This did not update the string.

And you can delete a complete string with the del keyword, but you cannot delete a character or slice.

>>> del work
>>> del text[3]


Traceback (most recent call last):
  File “<pyshell#25>”, line 1, in <module>
    del text[3]
TypeError: ‘str’ object doesn’t support item deletion
>>> del text[3:]


Traceback (most recent call last):
  File “<pyshell#26>”, line 1, in <module>
    del text[3:]
TypeError: ‘str’ object does not support item deletion

Concatenation and Membership in Python

1. Concatenation in Python

You can join two strings with the + operator.

This is called concatenation.

>>> 'come'+' '+'home'


‘come home’

You can also multiply a string by an integer.

>>> 'come'*3



But you cannot concatenate a string with an integer.

>>> 'help'+7


Traceback (most recent call last):
  File “<pyshell#29>”, line 1, in <module>
TypeError: can only concatenate str (not “int”) to str

2. Membership in Python

You can check whether a string is present in another.

You can do this with the ‘in’ and ‘not in’ operators.

>>> 'wire' in 'weird'


>>> 'cool' not in 'honesty'



Python String Length

To calculate the length of a string, you have the len() in-built function.

>>> len(text)



You can use this in a for-loop to traverse on a collection or you can use it for some other reasons.

Python also has other in-built functions and methods.

We will talk about them later.

>>> for index in range(len(text)):
  print(index, text[index])


0 A
1 y
2 u
3 s
4 h
5 i
7 b
8 o
9 u
10 g
11 h
12 t
14 a
16 p
17 e
18 n
19 !

String Methods and Functions in Pythonpython string methods and functions

Python has many in-built methods and functions for strings.

Today, in this Python strings article, we will discuss the most important ones.

1. strip() in Python

The strip() method removes whitespace around the string and returns the rest.

>>> ' hello '.strip()



You can also use lstrip() and rstrip() to remove the whitespace from only the left or the right.

>>> ' hello '.lstrip()


‘hello ‘
>>> ' hello '.rstrip()


‘ hello’

2. lower() and upper() in Python

We can convert a string to uppercase or lowercase using these methods.

They do not change the original string.

>>> text
'Ayushi bought a pen!'
>>> text.upper()
>>> text
'Ayushi bought a pen!'
>>> text.lower()
'ayushi bought a pen!'

3. split() in Python

We can split a string around a separator.

Let’s split the ‘text’ string around spaces.

>>> text.split(' ')


[‘Ayushi’, ‘bought’, ‘a’, ‘pen!’]

4. replace() in Python

We can also replace part of a string with another text.

This is done using the replace() method.

>>> text.replace('bought','buys')


‘Ayushi buys a pen!’

5. isdigit(), isalpha(), isalnum() in Python

We can use these methods to check whether a string is completely made of digits, alphabetical characters or both.

6. find() in Python

The find() method returns the first index where it finds a character.

>>> text.find('u')



If it does not find it, it returns -1.

>>> text.find('z')



7. Python join()

We can join values from an iterable using a specific character.

>>> ','.join(['1','2','3'])



8. startswith() and endswith() in Python

We can check whether a string starts with or ends with [endswith()] another string.

>>> text.startswith('Ayu')



9. max() and min() in Python

The max() and min() methods give us the characters with the highest and lowest values.

>>> max(text)


>>> min(text)


‘ ‘

Formatting Strings in Python

Strings are sequences of characters but can also hold values.

We can format a string and embed values in it.

There are 3 ways to do this in Python 3:

  • format() method
  • f-strings
  • % operator

1. format() method in Python

We can use the format() method to decide what variables to use to embed values in the string.

>>> cats=10
>>> 'She has {} cats'.format(cats)


‘She has 10 cats’

Here, it puts the value of cats in the curly braces part.

2. f-strings in Python

Python 2 does not have f-strings, but Python 3.6+ has them.

In this, you prefix the string with an ‘f’ and put variables in curly braces in the string.

>>> f'She has {cats} cats'


‘She has 10 cats’

3. % operator in Python

We can also use the % operator to define values, position and type in the string.

>>> 'She has %d cats' %(cats)


‘She has 10 cats’


In this blog, we learned about strings in Python and how to use, define and alter them.

We learned indexing, slicing, deleting, concatenating and calculating length, methods and functions and formatting strings.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.