Combining or Concatenating Strings in Python

Combining or Concatenating Strings in Python

It’s often useful to combine strings. For example, you might want to store a first name and a last name in separate variables, and then combine them when you want to display someone’s full name:

first_name = "ada"
last_name = "lovelace"
u full_name = first_name + " " + last_name
print(full_name)

Python uses the plus symbol (+) to combine strings. In this example, we use + to create a full name by combining a first_name, a space, and a last_name u, giving this result:

ada lovelace

This method of combining strings is called concatenation. You can use concatenation to compose complete messages using the information you’ve stored in a variable. Let’s look at an example:

first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
u print("Hello, " + full_name.title() + "!")

Here, the full name is used at u in a sentence that greets the user, and the title() method is used to format the name appropriately. This code returns a simple but nicely formatted greeting:

Hello, Ada Lovelace!

You can use concatenation to compose a message and then store the entire message in a variable:

first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
message = "Hello, " + full_name.title() + "!"
print(message)

This code displays the message “Hello, Ada Lovelace!” as well, but storing the message in a variable at u makes the final print statement at v much simpler.

Adding Whitespace to Strings with Tabs or Newlines

In programming, whitespace refers to any nonprinting character, such as spaces, tabs, and end-of-line symbols. You can use whitespace to organize your output so it’s easier for users to read. To add a tab to your text, use the character combination \t as shown

>>> print("Python")
Python
u >>> print("\tPython")
Python

To add a newline in a string, use the character combination \n:

>>> print("Languages:\nPython\nC\nJavaScript")
Languages:
Python
C
JavaScript

You can also combine tabs and newlines in a single string. The string “\n\t” tells Python to move to a new line, and start the next line with a tab. The following example shows how you can use a one-line string to generate four lines of output:

>>> print("Languages:\n\tPython\n\tC\n\tJavaScript")
Languages:
Python
C
JavaScript

Newlines and tabs will be very useful in the next two chapters when you start to produce many lines of output from just a few lines of code.

READ  Implementing a Pixel-perfect iOS UI Design

This article is an excerpt from A Hands-On, Project-Based Introduction to Programming by Eric Matthes

Reproduced with permission from No Starch Press

Leave a Reply

Your email address will not be published.