In this article, let’s see how strings are used in Python.
In Python, strings are sequences of characters. Strings can be any length and can include any character such as letters, numbers, symbols, and whitespace (spaces, tabs, new lines).
A string is created by entering text between two single or double quotation marks.
>>> "Hello World"
'Hello World'
To assign string to variable, add an equal sign and the string after variable name:
name = 'Hanna'
To assign a multiline string to a variable, we can use three quotes:
greeting = """Teacher: Good morning.
Students: Good morning, teacher"""
print(greeting)
>>> name = Anna
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Anna' is not defined
name = "Anna"
Backslashes are used to escape characters in a Python string.
For example, to print a string with quotation marks:
txt = "She said \"Hello\"."
print(txt)
# She said "Hello"
Other special characters:
\n
begins a new line.\'
single quote\\
backlash\t
pushes the content behind it 1 tab.\b
removes the space in front of it.\xnn
In addition, you can also use to print other special characters using the \xnn syntax, where n is 0->9, or a->f or A->F.To concatenate two strings, we can use the + operator.
a = "Hello"
b = "World"
c = a + " " + b
print(c)
We can also use print(f'string {variable}')
.
For example
>>> a = 'World'
>>> print(f'Hello {a}')
Hello World
Strings can be multiplied by integers. This produces a repeated version of the original string.
>>> print("Hello"*3)
HelloHelloHello
In Python, you can check if a string contains a substring by using the keyword in
or not in
.
>>> "H" in "Student"
False
>>> "I" in "I love Python"
True
We can select specific letters from this string using the index: stringName[index]
In there:
For example
>>> name = "strawberry"
>>> name[1]
t
If you try to select a non-integer index, we would get a TypeError.
>>> name = "strawberry"
>>> name[2.5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string indices must be integers
Negative indices
Negative indices count backward from the end of the string.
For example, string_name[-1]
is the last character of the string, string_name[-2]
is the second last character of the string, etc.
Strings are immutable, so we cannot change a string once it is created.
>>> name = "strawberry"
>>> name[0] = "B"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
We can select substring with the following syntax:
string_name[first_index:last_index]
When we slice a string, we create a new string that starts at the first_index and ends at (but excludes) the last_index.
For example
>>> name = "strawberry"
>>> name[2:5]
'raw'
We can also have open-ended selections.
>>> name = "strawberry"
>>> name[:5]
'straw'
>>> name[5:]
'berry'
We can use len() function to determine the length of a string.
length = len("Hello")
print(length)
# Output: 5
As indices start at 0, the final character in a string has the index of len(string_name) - 1
.
Example 1
>>> name = "strawberry"
>>> length = len(name) - 1
>>> name[length]
'y'
Example 2: To find the last three letters of a string:
last_three_letters = string_name[len(string_name)-3:]
Python has several string methods that we can use.
You can read more methods with string methods article.