Strings#

str data type#

Previously, we have already seen the data type for strings in Python. Today, we will take a closer look at them and learn about their new features. Strings come with some helpful built-in functions, often called methods, that let you perform various operations on them.

Methods#

Here are a few common ones (the full list of methods you can find here):

  • upper(): Transforms all characters to uppercase.

  • lower(): Converts all characters to lowercase.

  • replace(): Substitutes one part of the string with another.

  • split(): Breaks the string into a list using a separator.

text = "Random text"
upper_text = text.upper()
lower_text = text.lower()
repl_text = text.replace("Random", "Non-random")
words = text.split()

print("upper_text:", upper_text)
print("lower_text:", lower_text)
print("repl_text:", repl_text)
print("words:", words)
Hide code cell output
upper_text: RANDOM TEXT
lower_text: random text
repl_text: Non-random text
words: ['Random', 'text']

An important note is that strings are immutable objects. In all cases of method usage, we did not modify the original string.

print(text)
Hide code cell output
Random text

We can determine the length of a string using the same method as we did with lists. Additionally, we can use indexing:

for i in range(len(text)):
    print(str(i) + ": " + text[i])
Hide code cell output
0: R
1: a
2: n
3: d
4: o
5: m
6:  
7: t
8: e
9: x
10: t

Since strings are immutable, we cannot reassign specific elements.

text = "Random text"
text[0] = "W"
TypeError: 'str' object does not support item assignment

Converting a List to a String#

If you have a list and want to turn it into a single string, you can use the join() method. This method joins the elements of a list into a single string, with a specified separator in between.

fruits = ["apple", "banana", "cherry"]
fruit_string = "_".join(fruits)
print(fruit_string)
Hide code cell output
apple_banana_cherry

Converting a String to a List#

If you have a string and want to split it into a list of elements, you can use the split() method. This method breaks the string into parts using a specified separator.

fruit_string = "apple, banana, cherry"
fruits = fruit_string.split(", ")
print(fruits)
Hide code cell output
['apple', 'banana', 'cherry']

If you want to create a list where each symbol is a separate element, you can use the following approach:

name_str = "Vladimir"
name_list = list(name_str)
print(name_list)
Hide code cell output
['V', 'l', 'a', 'd', 'i', 'm', 'i', 'r']

f-Strings (Strings Formatting)#

Imagine you’re writing a letter, and you need to fill in details like the recipient’s name, the date, and the subject. It would be cumbersome to write everything from scratch every time, wouldn’t it? In programming, we often face similar situations where we need to combine text with dynamic values like variables. Enter f-strings - a feature in Python that makes this task easy, efficient, and even a little bit fun!

f-strings (formatted string literals) were introduced in Python 3.6 and have since become a favorite tool for many developers. They allow you to easily embed expressions inside string literals, using {} braces. Not only do f-strings make your code more readable, but they also make it more powerful and concise.

Note

Why Use f-Strings?

  • Simplicity: They’re straightforward and easy to understand.

  • Readability: They make your code cleaner and more readable.

  • Efficiency: They’re faster than older methods like str.format() and % formatting.

  • Versatility: You can embed any valid Python expression inside the braces.

Basic Usage of f-Strings#

Let’s start with a simple example. Suppose you want to print a sentence that includes a person’s name and age:

name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
Hide code cell output
My name is Alice and I am 30 years old.

What’s Happening?

  • The f before the string tells Python to treat it as a formatted string literal.

  • Inside the curly braces {}, you can put any variable, and Python will replace it with its value.

Embedding Expressions#

f-strings aren’t just for variables; you can also include expressions. For example:

a = 5
b = 10
print(f"The sum of {a} and {b} is {a + b}.")
Hide code cell output
The sum of 5 and 10 is 15.

What’s Happening?

  • Inside the curly braces, you’re performing the calculation {a + b}, and Python evaluates this expression before embedding the result into the string.

Formatting Numbers with f-Strings#

f-strings are also incredibly useful when you need to format numbers. Let’s say you want to display a price with two decimal places:

price = 49.12345
print(f"The price is {price:.2f}")
Hide code cell output
The price is 49.12

Breaking It Down:

  • {price:.2f}: Here, .2f tells Python to format the number to 2 decimal places.

You can even add commas to large numbers:

big_number = 1000000
print(f"The big number is {big_number:,}")
Hide code cell output
The big number is 1,000,000

What’s Happening?

  • {big_number:,}: The comma inside the braces tells Python to include commas as thousand separators.

Multiline f-Strings#

What if you want to create a string that spans multiple lines? No problem! f-strings support multiline formatting:

name = "Alice"
age = 30
address = "123 Maple Street"

info = (
    f"Name: {name}\n"
    f"Age: {age}\n"
    f"Address: {address}\n"
)

print(info)
Hide code cell output
Name: Alice
Age: 30
Address: 123 Maple Street

What’s Happening?

  • The parentheses () allow you to split the f-string across multiple lines for better readability.

  • Each line in the f-string is treated as part of the overall string.

f-Strings with Dictionaries#

You can even use f-strings to access values in dictionaries. Imagine you have a dictionary with some data:

person = {
    "name": "Alice",
    "age": 30,
    "city": "Wonderland"
}

print(f"{person['name']} is {person['age']} years old and lives in {person['city']}.")
Hide code cell output
Alice is 30 years old and lives in Wonderland.

What’s Happening?

  • You’re directly accessing the dictionary values inside the f-string by using the key names.

Advanced: Nesting f-Strings#

For the adventurous, you can even nest f-strings, though it’s a bit rare. Let’s see a quick example:

value = 4.56789
precision = 2
print(f"Value rounded to {precision} decimal places is {value:.{precision}f}.")
Hide code cell output
Value rounded to 2 decimal places is 4.57.

What’s Happening?

  • {value:.{precision}f}: Here, the precision variable controls how many decimal places are shown.

Note

f-strings are one of those features in Python that, once you start using, you’ll wonder how you ever lived without them. They’re not just about inserting variables into strings—they’re a powerful tool for formatting, calculating, and displaying data in a way that’s both readable and efficient.

As you continue coding in Python, you’ll find that f-strings become your best friend for handling strings. Whether you’re generating reports, creating logs, or just printing a message to the screen, f-strings make your code cleaner and more powerful.

Similarities between lists, tuples, and strings#

Despite their differences, lists, strings, and tuples also share some common features.

  • One common feature is that they all have a length, which can be obtained using the len function:

line = "The happiness of your life depends upon the quality of your thoughts."
numbers = [i * 10 for i in range(10)]
configs = (1920, 1080, "Windows")

print(len(line)) # number of symbols
print(len(numbers)) # number of elements 
print(len(configs)) # number of elements
Hide code cell output
69
10
3
  • Lists, strings, and tuples are iterable objects, allowing iteration over them using a for loop:

for elem in line:
    print(elem, end="")
print()

for elem in numbers:
    print(elem, end=" ")
print()

for elem in configs:
    print(elem, end=" ")
print()
Hide code cell output
The happiness of your life depends upon the quality of your thoughts.
0 10 20 30 40 50 60 70 80 90 
1920 1080 Windows 

Here we use an additional end argument in the print function, which allows us to replace the default new line symbol \n with a custom one.

  • We can check whether an element or substring is part of a list, tuple, or string by using the in operator:

print("happiness" in line)
print(10 in numbers)
print(1920 in configs)
Hide code cell output
True
True
True