Kahibaro
Discord Login Register

Combining text and variables

Why Combine Text and Variables?

Many programs need to display messages that include changing information: a user’s name, a score, a date, a calculated result, and so on. That information is usually stored in variables.

Combining fixed text (string literals) with values stored in variables is how you create clear, useful messages for users, logs, and reports.

In this chapter, you will see different ways to:

All of this builds on your knowledge of strings and basic operations.

Using `+` to Concatenate Strings

The simplest way to combine text and variables (that are already strings) is string concatenation with +.

first_name = "Ada"
last_name = "Lovelace"
full_name = first_name + " " + last_name
print("Hello, " + full_name + "!")

Output:

Hello, Ada Lovelace!

Key points:

This works only when all parts are strings.

Converting Non-Strings with `str()`

If you try to concatenate a string with a number directly, Python will raise an error.

age = 30
# print("Your age is " + age)  # This will cause an error

To fix this, convert the non-string value to a string using str():

age = 30
message = "Your age is " + str(age)
print(message)

Output:

Your age is 30

You’ll often use str() with:

Examples:

score = 98
print("Score: " + str(score))
pi = 3.14159
print("Pi is approximately " + str(pi))
is_logged_in = True
print("Logged in: " + str(is_logged_in))

Using Commas in `print()`

Another easy way to combine text and variables is to pass them as separate arguments to print(), separated by commas.

name = "Sam"
age = 25
print("Name:", name, "| Age:", age)

Output:

Name: Sam | Age: 25

What happens here:

So you don’t need to use str() or + when you do this.

Compare:

age = 25
# Using +
print("Age: " + str(age))
# Using commas
print("Age:", age)

Both produce:

Age: 25
Age: 25

Using commas is convenient for quick output, especially during testing or debugging.

Basic f-Strings (Formatted String Literals)

f-strings provide a powerful and readable way to combine text and variables. They work in Python 3.6+.

You write a string with a leading f and insert variables inside {}:

name = "Lina"
age = 21
message = f"Hello, {name}. You are {age} years old."
print(message)

Output:

Hello, Lina. You are 21 years old.

Advantages of f-strings:

Example with an expression inside {}:

length = 5
width = 3
print(f"Area: {length * width}")

Output:

Area: 15

Controlling Number Formatting in f-Strings

f-strings can format numbers directly inside {} using a colon and a format specifier.

Limiting Decimal Places

pi = 3.14159265
print(f"Pi (2 decimals): {pi:.2f}")
print(f"Pi (4 decimals): {pi:.4f}")

Output:

Pi (2 decimals): 3.14
Pi (4 decimals): 3.1416

Explanation:

Padding Numbers (Basic)

You can pad integers with leading zeros:

order_number = 42
print(f"Order ID: {order_number:05d}")

Output:

Order ID: 00042

Here:

Building Messages Step by Step

Sometimes you’ll construct a message gradually by adding pieces.

name = "Alex"
score = 87
message = "Player: " + name
message = message + " | Score: " + str(score)
print(message)

Or, using f-strings from the start:

name = "Alex"
score = 87
message = f"Player: {name}"
message += f" | Score: {score}"
print(message)

Output in both cases:

Player: Alex | Score: 87

Note:

Newlines and Special Characters in Combined Text

You can include special characters like the newline \n inside your strings to format the output.

name = "Aisha"
score = 120
message = f"Player: {name}\nScore: {score}"
print(message)

Output:

Player: Aisha
Score: 120

You can combine this with any of the techniques above.

Choosing a Technique

Here’s a quick comparison:

    "Total: " + str(total)
    print("Total:", total)
    print(f"Total: {total}")

In practice, f-strings are often the most convenient and readable option.

Practice Examples

Try to write code for these tasks:

  1. Store your name and city in variables and print a message like:
    Hello, Alice from London! using:
    • + and str() if needed
    • An f-string
  2. Ask the user for their name and age (you’ll formally learn input in a later chapter, but assume you have them in variables name and age), then create:
    • message1 = "Name: " + name + ", Age: " + str(age)
    • message2 = f"Name: {name}, Age: {age}"
      Print both.
  3. Given:
   product = "Book"
   price = 12.5

Print:

Views: 16

Comments

Please login to add a comment.

Don't have an account? Register now!