Methods for Strings
Raw strings are often not ready for display. We need some ways to format them so that they will appear as we want. The main tools to do it are via methods. Methods are “actions” innate to the specific object type (including strings) that can be invoked to modify it. Such methods are called in the form of <object>.<method>(<arguments>), where arguments are additional, often optional inputs that control the outcome of the methods.
For example, the methods lower, upper, capitalize, title will change all characters to lower/upper cases, or capitalize the first character of the string/every word. These are demonstrated by the code below:
some_words = "i love U!"print(some_words.lower())print(some_words.upper())print(some_words.capitalize())print(some_words.title())
The outputs are
i love u!I LOVE U!I love u!I Love U!
Formatting Strings
F-string
Frequently, we need to output a formatted line to provide useful information to the users, and it requires the insertion of variables into appropriate places with a specific format or appearance. The most basic way to do so is writing them as f-strings. This is done by simply adding the character f in front of the quoted strings. Then, we can use variables in the string by writing their name within a curly bracket {}. For example,
student = "Gracia"subject = "Maths"score = 99print(f"{student} got {score} marks in the {subject} test!")
produces Gracia got 99 marks in the Maths test!
format Method
A more advanced style will be utilizing the format method. It will take the arguments and put them according to the order as stated in the string. Using the same example, we can write
student = "Gracia"subject = "Maths"score = 99print("{0} got {2} marks in the {1} test!".format(student, subject, score))
and this will give the same result.
We can also be more specific by designating keywords for the format method. This is illustrated by another example:
GER = "Germany"SOV = "Soviet Union"USA = "USA"print("{country_A} has declared war on {country_B}.".format(country_A=GER, country_B=SOV))print("{country_A} has declared war on {country_B}.".format(country_A=USA, country_B=GER))
This produces
Germany has declared war on Soviet Union.USA has declared war on Germany.
Formatting Numbers
Sometimes, a number may be too lengthy or need to be in a specific precision (e.g. decimals) to be displayed. We can use the :.<decimal_place>f phrase inside the curly bracket {} for both cases above to adjust the number of valid decimal places. (Don’t forget the .!) Using the exercise in the last tutorial as an example, we may write
T_celsius = 10T_fahrenheit = 9/5 * (T_celsius + 32)print(f"Temperature Conversion Result: {T_fahrenheit:.3f} degree F.")print("Temperature Conversion Result: {:.3f} degree F.".format(T_fahrenheit))
Either way, it will print out Temperature Conversion Result: 75.600 degree F. An alternative is :.<decimal_place>g which will remove any insignificant zeros. (Try changing to it!)
We also have :.<decimal_place>% and :.<decimal_place>e for formatting percentages and scientific notation. For example,
stock = "Yuzusoft"buying_price = 1810.4selling_price = 2005.7profit = (selling_price - buying_price)/buying_priceprint(f"Your stock of {stock} was bought at {buying_price:.0f} dollars " \ f"and sold at {selling_price:.0f} dollars. " \ f"The profit percentage is {profit:.2%}.")
produces
Your stock of Yuzusoft was bought at 1810 dollars and sold at 2006 dollars. The profit percentage is 10.79%.
The \ indicates a line break for continuation. The :.0f trick is to round off the number to the nearest integer.
Exercise
Our Earth has a radius of approximately \(6378137 \text{ m}\) at the Equator. Print a sentence to convey this piece of information, but in scientific notation with \(3\) d.p and the unit of km. Try to do that for other planets.
Suggested Solution
One possible way to do it is
planet_name = "Earth"planet_radius = 6378137print(f"The radius of {planet_name} is about {(planet_radius/1000):.3e} km.")
This prints The radius of Earth is about 6.378e+03 km. as expected.







Leave a Reply