Python Strings – Get ready to work with sequence of characters

In our last blog, we learned about operators in Python. Now 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.

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

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

If we perform indexing left to right, in the above 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

Negative indexing happens right to left. 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.

>>>text[-13]

Output:

‘b’

Next in TechVidvan’s Python strings article, we will see how to slice strings in Python.

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

1. Concatenation

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

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

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

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

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

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

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

6. find()

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. join()

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

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

Output:

‘1,2,3’

8. startswith() and endswith()

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

>>> text.startswith('Ayu')

Output:

True

9. max() and min()

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

>>> max(text)

Output:

‘y’
>>> min(text)

Output:

‘ ‘

Now, in Python Strings article, let’s see how to format strings in Python.

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

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

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

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.

If you have any doubts in TechVidvan’s Python Strings article, mention them in the comment section. We will be happy to help you!!

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.