A string is a collection of one or more alphabet characters.
Python does not have a character data type, a single character is simply a string with a length of 1.
In Python, the string texts are declared in either single ('
)or double ("
) quotation marks.
"Hello"
'Hello'
Here, the Hello string text is declared in single quotes as well as in double quotes, and both strings are equal.
To display string in the console, you can use the print()
function.
print("Hello")
Hello
In this example, we printed the Hello
text by using a print()
function.
A string is assigned to a variable by preceding its name with an equal sign (=
) and the string itself.
message = "Hello"
print(message)
x is none.
In the above example, the Hello
string is assigned to one variable called message
, and the variable name is printed in the console by using the print()
function.
In Python, you cannot declare the multiline string text with one double quote ("
) or one single quote ('
).
To declare a multiline string text, use triple double quotes ("""
) or triple single quotes ('''
).
You can use the multiline string for documentation purposes in Python, that's why a multiline string is also called a doc string.
"""Hello
World"""
'''Hello
World'''
message = """Hello
World"""
print(message)
Hello
World
As you can see in the example above, we used triple-double quotes ("""
) to declare the Hello World
string text on multiple lines.
Strings in Python are arrays representing the sequence of characters.
The square brackets ([]
) is used to access items (characters) of the string.
message = "Hello world"
print(message[0])
H
Here, we accessed the first character (H
) of the string using the index (0
) position.
In Python, strings are arrays, so we can loop through their characters using a for
loop.
for i in "Hello":
print(i)
H
e
l
l
o
Here, we interate the "Hello"
string text by using a for
loop statement and also printed each character in the console with each iteration.
Use the Python len()
function to get the length of the string text.
print(len("Hello world"))
11
Here, the length of the "Hello world"
string is 11
.
Using not
in
keyword, you can check a certain character, word or phrase not present in the string.
print("Hello" not in "Hello world")
False
Here, If the "Hello"
word is not present in the string, then it returns a True
boolean value, otherwise, it returns a False
. The "Hello"
word is present in the "Hello world"
string, that's why it returned a False
value.
Using in
keyword, you can check a certain character, word or phrase present in the string.
print("Hello" in "Hello world")
True
Here, If the "Hello"
word is present in the string, then it returns a True
boolean value, otherwise, it returns a False
. The "Hello"
word is present in the "Hello world"
string, that's why it returned a True
value.