Python Strings – Get ready to work with sequence of characters

In this article, we will delve into Python strings, which are sequences of characters similar to character arrays in C++. We’ll cover the fundamentals of declaring strings, indexing and slicing them to access and manipulate specific parts, and formatting them for various uses. Additionally, we’ll explore how to delete strings and make use of Python’s rich set of built-in methods and functions that make string manipulation straightforward and powerful. Whether you’re new to programming or experienced, this guide will help you master working with strings in Python.

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.

name=’Ayushi’

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

>>> str(123)

Output:

‘123’
>>> str('Hi')

Output:

‘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]

Output:

‘b’
>>> text[21]

Output:

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

2. Negative Indexing in Python

Negative indexing allows you to access characters in a string from right to left. In this system, the index -1 refers to the last character of the string, -2 refers to the second last, and so on. This feature is particularly useful for quickly accessing the end of a string without needing to know its length. For example, in the string “Python”, the index -1 would return ‘n’ and the index -2 would return ‘o’. Negative indexing provides a convenient way to work with elements at the end of a sequence efficiently.

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

>>>text[-13]

Output:

‘b’

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]

Output:

‘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]

Output:

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:]

Output:

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'

Output:

‘come home’

You can also multiply a string by an integer.

>>> 'come'*3

Output:

‘comecomecome’

But you cannot concatenate a string with an integer.

>>> 'help'+7

Output:

Traceback (most recent call last):
  File “<pyshell#29>”, line 1, in <module>
    ‘help’+7
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'

Output:

False
>>> 'cool' not in 'honesty'

Output:

True

Python String Length

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

>>> len(text)

Output:

20

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])

Output:

0 A
1 y
2 u
3 s
4 h
5 i
6
7 b
8 o
9 u
10 g
11 h
12 t
13
14 a
15
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()

Output:

‘hello’

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

>>> ' hello '.lstrip()

Output:

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

Output:

‘ 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()
'AYUSHI BOUGHT A PEN!'
>>> 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(' ')

Output:

[‘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')

Output:

‘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')

Output:

2

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

>>> text.find('z')

Output:

-1

7. Python join()

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

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

Output:

‘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')

Output:

True

9. max() and min() in Python

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

>>> max(text)

Output:

‘y’
>>> min(text)

Output:

‘ ‘

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)

Output:

‘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'

Output:

‘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)

Output:

‘She has 10 cats’

Summary

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.

TechVidvan Team

The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today’s tech industry.