Strings
Strings in python are surrounded by either single quotation marks, or double
quotation marks.
'hello' is the same as "hello".
Quotes Inside Quotes
You can use quotes inside a string, as long as they don't match the quotes
surrounding the string:
Example
print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Example
You can use 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)
Or three single quotes:
Example
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)
Strings are Arrays
Like many other popular programming languages, strings in Python are
arrays of unicode characters.
However, Python does not have a character data type, a single character is
simply a string with a length of 1.
Square brackets can be used to access elements of the string.
Example
Get the character at position 1 (remember that the first character has the
position 0):
a = "Hello, World!"
print(a[1])
Negative Indexing with Strings
String in Python are also sequences so we can use negative indexing to access
characters from the end of the string.
s = "Python"
# Accessing characters using negative indexing
print(s[-1]) #(last character)
print(s[-3]) #(third last character)
Looping Through a String
Since strings are arrays, we can loop through the characters in a string, with
a for loop.
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
String Length
To get the length of a string, use the len() function.
Example
The len() function returns the length of a string:
a = "Hello, World!"
print(len(a))
Slicing
You can return a range of characters by using the slice syntax.
Syntax:
slice(start, end, step)
Parameter Values
Parameter Description
start Optional. An integer number specifying at which position to start the slicing.
Default is 0
end An integer number specifying at which position to end the slicing (not
included)
step Optional. An integer number specifying the step of the slicing. Default is 1
Example
Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])
Get the characters from the start to position 5 (not included):
b = "Hello, World!"
print(b[:5])
Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:])
Get the characters from: "o" in "World!" (position -5) to (position -2):, but not
included: "d" in "World!"
b = "Hello, World!"
print(b[-5:-2])
How to reverse a String in Python
There is no built-in function to reverse a String in Python.
The fastest (and easiest?) way is to use a slice that steps backwards, -1.
Example
Reverse the string "Hello World":
txt = "Hello World"[::-1]
print(txt)
Note: In this particular example, the slice statement [::-1] means start at
the end of the string and end at position 0, move with the step -1,
negative one, which means one step backwards.
Python - Modify Strings
Python has a set of built-in methods that you can use on strings.
Upper Case
Example
The upper() method returns the string in upper case:
a = "Hello, World!"
print([Link]())
Lower Case
Example
The lower() method returns the string in lower case:
a = "Hello, World!"
print([Link]())
Remove Whitespace
Whitespace is the space before and/or after the actual text, and very often
you want to remove this space.
Example
The strip() method removes any whitespace from the beginning or the end:
a = " Hello, World! "
print([Link]()) # returns "Hello, World!"
Replace String
Example
The replace() method replaces a string with another string:
a = "Hello, World!"
print([Link]("H", "J")
Split String
The split() method returns a list where the text between the specified
separator becomes the list items.
Example
The split() method splits the string into substrings if it finds instances of the
separator:
a = "Hello, World!"
print([Link](",")) # returns ['Hello', ' World!']
a = "Hello World!"
b = [Link](" ")
print(b) # returns ['Hello', ' World!']
String Format
As we learned in the Python Variables chapter, we cannot combine strings
and numbers like this:
Example
age = 36
#This will produce an error:
txt = "My name is John, I am " + age
print(txt) //Error
But we can combine strings and numbers by using f-strings or
the format() method!
F-Strings
F-String was introduced in Python 3.6, and is now the preferred way of
formatting strings.
To specify a string as an f-string, simply put an f in front of the string literal,
and add curly brackets {} as placeholders for variables and other operations.
Example
Create an f-string:
age = 36
txt = f"My name is John, I am {age}"
print(txt)
Format() method
The format() method formats the specified value(s) and insert them inside
the string's placeholder.
The placeholder is defined using curly brackets {}. Read more about the
placeholders in the Placeholder section below.
The format() method returns the formatted string.
Example
Using different placeholder values:
txt1 = "My name is {fname}, I'm {age}".format(fname ="John", age
= 36)
txt2 = "My name is {0}, I'm {1}".format("John",36)
txt3 = "My name is {}, I'm {}".format("John",36)