4. Strings#

4.1. What is a String?#

A string is a sequence of characters enclosed in single (') or double (") quotation marks. Both styles work the same way in Python.

my_string = "Hello, World!"
another_string = 'Python is fun!'

You can also create multi-line strings using triple quotes (''' or """). You might remember that we also use triple quotes for multi-line comments. That is because triple-quoted blocks are actually multi-line strings, not real comments. If you write them and don’t assign them to a variable, Python just ignores them — so they seem like comments.

multi_line = """This is
a string
spanning 3 lines."""

Strings are used whenever you need to work with text data.

4.2. Basic String Operations#

You can combine, repeat, and access parts of strings in Python. For this, mathematical operators are often used, resembling operations of numerical variables.

Concatenation (joining strings)#

You can join strings together using the + operator.

greeting = "Hello"
name = "Alice"
message = greeting + ", " + name + "!" # joining the two string variables with the strings ", " and "!"; Note that ", " has a space 
print(message) # Output: Hello, Alice!
Hello, Alice!

Repetition (repeating strings)#

You can repeat a string multiple times using the * operator and an integer value stating how often it should be repeated.

laugh = "ha" * 5
print(laugh) # Output: hahaha
hahahahaha

Accessing characters (indexing)#

You can access individual characters in a string by putting square brackets [ ] after the string with the index of the character that you want to access inside it.

text = "Python"
print(text[0]) # Output: P
print(text[1]) # Output: y
P
y

Indexing in Python

In Python, indexing starts at 0.
This means that the first character or item has index 0, the second has index 1, and so on.

Visual example:

Index:    0   1   2   3   4   5
Letter:   P   y   t   h   o   n

4.3. Common String Methods#

Python provides many useful methods to work with strings.

A method is a function that is defined specifically for a certain data type (or class - you will learn exactly what they are in Chapter …). It is not used like a standard function where you just write the function name and put your variable name inside as an argument, e.g. print(text), but by adding it to the end of your variable name separated with a period ., e.g. text.method(). Methods still have the brackets in the end where you might have to insert additional arguments needed to run it.

Some of the most common methods that are defined for string variables are:

  • .lower(): Converts all characters to lowercase.

  • .upper(): Converts all characters to uppercase.

  • .strip(): Removes spaces from the beginning and end.

  • .replace(old, new): Replaces part of a string with something else for every occurrence of it. Parameters:

    • old: The part of the string you want replaced

    • new: What you replace it with

  • .find(substring): Finds the index of the first occurrence of a substring. Parameters:

    • substring: The substring/character that you want to find in your string

You can also chain methods together

sentence = "   This is Python!   "
print(f'Original sentence: {sentence}') # Output: "   This is Python!   "

stripped_sentence = sentence.strip() # removes leading and trailing whitespace
print(f'Stripped sentence without whitespace: {stripped_sentence}') # Output: "This is Python!"

lowercase_sentence = sentence.lower() # converts all characters to lowercase
print(f'Lowercase sentence: {lowercase_sentence}') # Output: "   this is python!   "

uppercase_sentence = sentence.upper() # converts all characters to uppercase
print(f'Uppercase sentence: {uppercase_sentence}') # Output: "   THIS IS PYTHON!   "

replaced_word_sentence = sentence.replace("Python", "Magic") # replaces "Python" with "Magic"
print(f'Replaced a full word in the sentence: {replaced_word_sentence}') # Output: "   This is Magic!   "

replaced_character_sentence = sentence.replace(" ", "_") # replaces all spaces with underscores
print(f'Replaced white space with underscore: {replaced_character_sentence}') # Output: "___This_is_Python!___"

found_unique_word = sentence.find("Python") # finds the index of the first occurrence of "Python"
print(f'Found "Python" at index: {found_unique_word}') # Output: 7

found_multiple_character = sentence.find("i") # finds the index of the first occurrence of "i"
print(f'Found "i" for the first time at index: {found_multiple_character}') # Output: 5

#you can also chain methods
lowercase_stripped_sentence = sentence.strip().lower() # removes leading and trailing whitespace and converts all characters to lowercase
print(f'Stripped and lowercase sentence (in one step): {lowercase_stripped_sentence}') # Output: "this is python!"
Original sentence:    This is Python!   
Stripped sentence without whitespace: This is Python!
Lowercase sentence:    this is python!   
Uppercase sentence:    THIS IS PYTHON!   
Replaced a full word in the sentence:    This is Magic!   
Replaced white space with underscore: ___This_is_Python!___
Found "Python" at index: 11
Found "i" for the first time at index: 5
Stripped and lowercase sentence (in one step): this is python!

4.4. Quick Practice#

Try these small challenges:

  • Create a variable called quote and assign your favourite quote as a string. Add extra space at either the start or end.

  • Print the quote in uppercase letters.

  • Print the quote with no extra spaces at the start or end.

# Put your code here
💡 Solution
quote = "  Machine learning is transforming how we diagnose, predict, and understand diseases.  "
print(quote.upper())
print(quote.strip())