Strings in Python

This tutorial will teach you how to use the Python string and its fundamental operations.

A character string is a collection of characters. Anything inside quotations is a string in Python. You have the option of using single or double quotations. For instance:

message = 'This is a string in Python'
message = "This is also a string"

If a string contains a single quotation, it should be enclosed in double quotes, as shown below:

message = "It's a string"

You can also use single quotes when a string contains double quotations:

message = '"Beautiful is better than ugly.". Said Tim Peters'

The backslash is used to escape the quotations (). For instance:

message = 'It\'s also a valid string'

The backslash character () is treated differently by the Python interpreter. If you don’t want it to do that, add the letter r before the first quote to utilise raw strings. For instance:

message = r'C:\python\bin'

How to Create Multiline Strings in Python?

The triple-quotes “””…””” or “‘…”‘ are used to span many lines in a string. As an example:

help_message = '''
Usage: mysql command
    -h hostname     
    -d database name
    -u username
    -p password 
'''

print(help_message)

If you run the programme, you’ll get the following results:

Usage: mysql command
    -h hostname
    -d database name
    -u username
    -p password

f-strings and Python variables

You may want to use the values of variables in a string on occasion.

You could want to use the name variable’s value inside the message string variable, for example:

name = 'John'
message = 'Hi'

Place the letter f before the beginning quote mark and the brace around the variable name to accomplish this:

name = 'John'
message = f'Hi {name}'
print(message)

Python will substitute the value of the name variable for the name. On the screen, the code will display the following:

Hi John

A format string, or f-string for short, is the message. The f-string was added to Python 3.6.

How to Concatenate Python Strings?

Python automatically concatenates the string literals when they are placed adjacent to each other. For instance:

greeting = 'Good ' 'Morning!'
print(greeting)

Output

Good Morning!

The operator + is used to join two string variables together.

greeting = 'Good '
time = 'Afternoon'

greeting = greeting + time + '!'
print(greeting)

Output

Good Afternoon!

How to Access String Elements in Python?

An index can be used to retrieve the elements of a string because it is a sequence of characters. The index of the first character in the string is zero.

The following example demonstrates how to use an index to access elements:

str = "Python String"
print(str[0]) # P
print(str[1]) # y

How does it work?

  • Create a variable called “Python String” to hold a string.
  • Then, using square brackets [] and indexes, get the first and second characters of the string.
  • Python returns the character starting from the end of the string when you specify a negative index. For instance:
str = "Python String"
print(str[-1])  # g
print(str[-2])  # n

The indexes of the string “Python String” are shown below:

+---+---+---+---+---+---+---+---+---+---+---+---+---+
| P | y | t | h | o | n |   | S | t | r | i | n | g | 
+---+---+---+---+---+---+---+---+---+---+---+---+---+
  0   1   2   3   4   5   6   7   8   9   10  11  12
-12  -11  -10 -9  -8  -7  -6  -5  -4  -3  -2  -1   0 

How to Get the Length of the String in Python?

The len() method is used to determine the length of a string. For instance:

str = "Python String"
str_len = len(str)
print(str_len)

Output

13

How to Slice String in Python?

Slicing is a method for extracting a substring from a string. For instance:

str = "Python String"
print(str[0:2])

Output

Py

The str[0:2] function returns a substring that contains the characters from 0 (included) to 2 (excluded) (excluded).

The slicing syntax is as follows:

string[start:end]

The substring always contains the first character and excludes the last string.

Both the beginning and the end are optional. It defaults to zero if you leave out the start. If the end is omitted, the string’s length is assumed.

Immutable Python Strings

Strings in Python are immutable. It indicates you won’t be able to modify the string. If you update one or more characters in a string, for example, you’ll get an error:

str = "Python String"
str[0] = 'J'
Traceback (most recent call last):
  File "app.py", line 2, in <module>
    str[0] = 'J'
TypeError: 'str' object does not support item assignment</module>

When you wish to change a string, you must generate a new one from the old one. For instance:

str = "Python String"
new_str = 'J' + str[1:]
print(new_str)

Output

Jython String