Strings in Python are surrounded by either single quotation marks, or double quotation marks.
'hello' is exactly the same as "hello".
You can display a string literal with the print() function, or assign it to a variable.
Input:
# Both single and double quotes work perfectly
print("Hello")
print('Hello')
# Assigning to a variable
a = "Hello"
print(a)Output:
Hello
Hello
Hello
If you need to use a quote character inside your string, you must wrap the entire string in the opposite type of quote to prevent a syntax error!
Input:
# Wrapping in double quotes because there is a single quote inside
sentence_1 = "It's alright"
# Wrapping in single quotes because there are double quotes inside
sentence_2 = 'He is called "Johnny"'
print(sentence_1)
print(sentence_2)Output:
It's alright
He is called "Johnny"
You can assign a multiline string to a variable by using three quotes (either """ or '''). This is incredibly useful for long text blocks, poems, or formatted output.
Input:
# Using three double quotes
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)Output:
Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.
(Notice how the line breaks in the code are perfectly preserved in the output!)
Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.
However, Python does not have a "character" data type. A single character is simply a string with a length of 1. Because strings are arrays, you can access individual characters using square brackets [].
Input:
# Accessing the first character (Python is 0-indexed)
a = "Hello, World!"
print("First character:", a[0])
# Accessing the 8th character (Index 7)
print("Eighth character:", a[7])
# Accessing the last character using negative indexing
print("Last character:", a[-1])Output:
First character: H
Eighth character: W
Last character: !
If you try to access an index that is larger than the length of the string, your program will crash.
Input:
word = "Cat"
# print(word[5]) # ERROR! The string only goes up to index 2Output:
IndexError: string index out of range