Python Strings – A Detailed Introduction
In Python, strings are one of the most fundamental data types and are used to store sequences of characters. They can be enclosed in either single quotes ('
) or double quotes ("
), and both notations are treated identically.
print("Hello")
print('Hello')
Inserting Quotes Within Strings
You can include quotation marks inside a string by alternating the enclosing quotation style. Here are some examples:
print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')
Assigning Strings to Variables
Strings can be assigned to variables using the equals sign:
a = "Hello"
print(a)
Multiline Strings
Python allows the creation of multiline strings using triple quotes (either single or double):
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)
Note: Line breaks are preserved in the output exactly as written in the code.
Strings as Arrays
Strings in Python are arrays of Unicode characters. Python lacks a dedicated character data type, so individual characters are simply strings of length one. You can access elements in a string using square brackets:
a = "Hello, World!"
print(a[1]) # Outputs 'e'
Iterating Through Strings
You can loop through the characters of a string using a for
loop:
for x in "banana":
print(x)
To explore loops in greater detail, refer to the Python For Loops section on Devyra.
Finding String Length
The len()
function returns the number of characters in a string:
a = "Hello, World!"
print(len(a))
Checking String Content
To verify whether a particular phrase or character exists within a string, use the in
keyword:
txt = "The best things in life are free!"
print("free" in txt)
You can also use this within an if
statement for conditional logic:
if "free" in txt:
print("Yes, 'free' is present.")
Negating String Presence
To determine if a character or phrase is absent from a string, use the not in
keyword:
print("expensive" not in txt)
Within a condition:
if "expensive" not in txt:
print("No, 'expensive' is NOT present.")
To deepen your understanding of conditional logic, explore the Python If…Else section on Devyra.