Python Strings
Python Strings
Python Strings
Example:
print("Hello")
print('Hello')
Hello
Hello
Example:
print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')
It's alright
He is called 'Johnny'
He is called "Johnny"
Assign String to a Variable
Assigning a string to a variable is done with the variable name followed by an
equal sign and the string:
Example:
a = "Hello"
print(a)
Hello
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Example
You can use three double quotes:
Or
three single quotes:
xample:
a = "Hello, World!"
print(a[1])
for x in "banana":
print(x)
b
a
n
a
n
a
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))
13
Check String
To check if a certain phrase or character is present in a string, we can use the
keyword in.
Example
Check if "free" is present in the following text:
True
Use it in an if statement:
Example
Print only if "free" is present:
Check if NOT
To check if a certain phrase or character is NOT present in a string, we can use
the keyword not in.
Example
Check if "expensive" is NOT present in the following text:
True
Use it in an if statement:
Example
print only if "expensive" is NOT present:
Specify the start index and the end index, separated by a colon, to return a part
of the string.
Example
Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])
llo
Example
Get the characters from the start to position 5 (not included):
b = "Hello, World!"
print(b[:5])
Hello
Example
Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:])
llo, World!
Negative Indexing
Use negative indexes to start the slice from the end of the string:
Example
Get the characters:
From: "o" in "World!" (position -5)
To, but not included: "d" in "World!" (position -2):
b = "Hello, World!"
print(b[-5:-2])
orl
Modify Strings
Upper Case
Example
The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())
HELLO, WORLD!
Lower Case
Example
The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())
hello, world!
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:
Hello, World!
Replace String
Example
The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J"))
Jello, World!
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(a.split(",")) # returns ['Hello', ' World!']
String Concatenation
String Concatenation
To concatenate, or combine, two strings you can use the + operator.
Example
Merge variable a with variable b into variable c:
a = "Hello"
b = "World"
c = a + b
print(c)
HelloWorld
Example
To add a space between them, add a " ":
a = "Hello"
b = "World"
c = a + " " + b
print(c)
Hello World
String Format
As we learned in the Python Variables chapter, we cannot combine strings and
numbers like this:
Example
age = 36
txt = "My name is John, I am " + age
print(txt)
F-Strings
F-String was introduced in Python 3.6, and is now the preferred way of
formatting strings.
Example
Create an f-string:
age = 36
txt = f"My name is John, I am {age}"
print(txt)
My name is John, I am 36
price = 59
txt = f"The price is {price} dollars"
print(txt)
Example
Display the price with 2 decimals:
price = 59
txt = f"The price is {price:.2f} dollars"
print(txt)
Escape Characters
Other escape characters used in Python:
Code Result
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
String Methods
Python has a set of built-in methods that you can use on strings.
Note: All string methods return new values. They do not change the original string.
Method Description
endswith Returns true if the string ends with the specified value
()
index() Searches the string for a specified value and returns the position
of where it was found
isalpha() Returns True if all characters in the string are in the alphabet
isascii() Returns True if all characters in the string are ascii characters
islower() Returns True if all characters in the string are lower case
isupper() Returns True if all characters in the string are upper case
partition( Returns a tuple where the string is parted into three parts
)
rfind() Searches the string for a specified value and returns the last
position of where it was found
rindex() Searches the string for a specified value and returns the last
position of where it was found
rpartition Returns a tuple where the string is parted into three parts
()
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
startswit Returns true if the string starts with the specified value
h()
swapcas Swaps cases, lower case becomes upper case and vice versa
e()