BIT502 Fundamentals of Programming : Contents : Topic 2: Programming concepts : Operations and calculations : String formatting
two solutions to make string formatting easy and to avoid the above situation.
- a formatted string
The formatted string has the following syntax:
f: "some_string_with_variable_insertion"
Wherever we are required to insert a variable, we use{name_of_variable}
. - using a placeholder.(use the operator ‘%’ as a placeholder within a string)
age = 23
weight = 84
height = 1.89
name = "John Smith"
formatted_text = f"Hi. My name is {name}. I am {str(age)} years old. My weight is {str(weight)}Kg and height is {str(height)}m"
print(formatted_text)
Output:
Hi. My name is John Smith. I am 23 years old. My weight is 84Kg and height is 1.89m
name = "Marsha"
age = 47
height = 1.63
message1 = "My name is %s." % name # %s is a string placeholder inside the string. Note that the % outside the string
#indicates which data to be replaced against the placeholder. The data type should
#match the placeholder (in this case %s is for string and the variable name is string)
message2 = "I am %d years old" % age # %d is for integer
message3 = "My height is %g m." % height # %f is for float
#For multiple insertion
big_message = "My name is %s. I am %d years old and my height is %g metres." % (name,age,height)
print(message1)
print(message2)
print(message3)
print(big_message)
Output
My name is Marsha.
I am 47 years old
My height is 1.63 m.
My name is Marsha. I am 47 years old and my height is 1.63 metres.
name = "Sarah"
number_courses = 3
easy_course = "BIT502"
message1 = "%s is enrolled in %d courses." % (name,number_courses)
message2 = f"Hi there! {message1} The easiest course is {easy_course}"
print(message2)
Output
Hi there! Sarah is enrolled in 3 courses. The easiest course is BIT502