KAHIBARO Bookshelves
Discord Login Register

4.4. 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:

  • Join text and variable values
  • Avoid common errors when combining strings and other data types
  • Format messages in readable and flexible ways

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:

  • + between strings joins them together.
  • You can include spaces as separate string pieces: " ".

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:

  • Integers: int
  • Floats: float
  • Booleans: bool

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:

  • print() automatically converts non-strings to strings.
  • print() automatically adds a space between each argument.

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:

  • You don’t need + or str().
  • You can see the structure of the message clearly.
  • You can include expressions, not just simple variable names.

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:

  • :.2f means: format as a floating-point number with 2 decimal places.
  • :.4f means: 4 decimal places.

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:

  • 05d means: integer (d), width 5, pad with zeros on the left.

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:

  • message += ... is a shorthand for message = message + ....

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:

  • + with str()
    • Good for: simple, quick combinations when you know everything is a string (or you’re comfortable calling str()).
    • Example:
    "Total: " + str(total)
  • Commas in print()
    • Good for: quick output while testing; you don’t care about exact spacing or format details.
    • Example:
    print("Total:", total)
  • f-strings
    • Good for: most real programs; clear, readable, flexible formatting.
    • Example:
    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:

  • Book costs 12.5
  • Book costs 12.50 (with exactly 2 decimal places)
    using f-strings.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms