How can I add string, then a variable, then a string again?
How can I add string, then a variable, then a string again?
I am a novice Python user using 3.6 on Python IDLE. I wrote a program for school to calculate distance traveled depending on speed and time. I was able to get the program to display the numerical value of the distance which is great, but I would like it to also show "miles" after the numerical value that way it shows the unit of measurement. Here is my code:
def main():
#variable for speed
speed = 60
#variables for time
time1 = 5
time2 = 8
time3 = 12
#variables for distance
distance1 = time1 * speed
distance2 = time2 * speed
distance3 = time3 * speed
#display the distance equations
print ("The distance the car will travel in 5 hours is ", distance1 + " miles")
print ("The distance the car will travel in 8 hours is ", distance2 + "miles")
print ("The distance the car will travel in 12 hours is ", distance3 + "miles")
You can see where I tried to concatenate the first string, variable, and the second string. This breaks my code. Any help is appreciated!
str()
str(distance1)
1 Answer
1
I suggest using the latest coolest formatting option implemented in Python, which is the formatted string literals:
print(f"The distance the car will travel in 5 hours is distance1 miles")
But you may also do any of these:
print("The distance the car will travel in 5 hours is miles".format(distance1))
print("The distance the car will travel in 5 hours is %s miles" % distance1)
print("The distance the car will travel in 5 hours is", distance1, "miles")
print("The distance the car will travel in 5 hours is" + str(distance1) + " miles")
This worked perfectly! I used the new formatting you suggested, really nice and simple. Thanks a million zvone.
– Rene Delgado
Sep 1 at 23:01
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
You need to call
str()on numerical values, sostr(distance1).– roganjosh
Sep 1 at 22:48