String Formatting¶
Date published: 2018-04-01
Category: Python
Subcategory: Beginner Concepts
Tags: strings
Strings allow you to hold textual data in Python.
Often times, you'll want to print a string and pass in a variable.
You can use the format
method on strings to pass in a variable.
In [27]:
Copied!
name = "Dan"
"Hi my name is: {}".format(name)
name = "Dan"
"Hi my name is: {}".format(name)
Out[27]:
'Hi my name is: Dan'
A more useful example would be to print grammatically correct English sentences about the data.
In the example below, we want to print the results of the scooter ride data below to easily highlight the data's meaning.
In [28]:
Copied!
scooter_ride_data = {1: ['4-01-2018', 4.5],
2: ['4-01-2018', 3.1],
3: ['4-01-2018', 6.2]
}
scooter_ride_data = {1: ['4-01-2018', 4.5],
2: ['4-01-2018', 3.1],
3: ['4-01-2018', 6.2]
}
Notice below if we want to pass in several variables, we must provide a numerical counter in the braces {}
.
In [29]:
Copied!
print("Details of today's rides:")
for ride_details in scooter_ride_data.items():
print("Ride #{0} started on {1} and distance traveled was {2} miles".format(ride_number, start_time, distance_miles))
print("Details of today's rides:")
for ride_details in scooter_ride_data.items():
print("Ride #{0} started on {1} and distance traveled was {2} miles".format(ride_number, start_time, distance_miles))
Details of today's rides: Ride #3 started on 4-01-2018 and distance traveled was 6.2 miles Ride #3 started on 4-01-2018 and distance traveled was 6.2 miles Ride #3 started on 4-01-2018 and distance traveled was 6.2 miles