MORE ON DICTIONARY KEYS 有關字典鍵的更多信息 <<
Previous Next >> Solutions 解決方案
String formatting 字符串格式
We’ve talked about strings a lot on this blog:
But we want to introduce one more optional concept for this exercise related to string formatting. There are a number of ways to format strings in Python, so I am just going to show you one quick way for a scenario you find yourself in often while programming.
A common scenario is like this: you want to print both a string and a number in the same line using one print() statement. You can solve this problem like so:
我們在此博客上討論了很多字符串:
但是,我們想為此練習引入與字符串格式化有關的另一個可選概念。有很多方法可以用Python格式化字符串,因此,我將向您展示一種快速編程的方法,以解決您經常在編程時遇到的情況。
常見的情況是這樣的:您想使用一個print()語句在同一行中同時打印字符串和數字。您可以這樣解決此問題:
>>> a = 1
>>> b = 10
>>> print("my number is " + str(a) + " and his number is " + str(b))
my number is 1 and his number is 10
But it gets tedious to use + and str(). Instead, you can use the .format() method to cast (i.e. transform) your number into a string when it gets printed.
但是使用+和會很麻煩str()。相反,你可以使用.format()的方法來投(即變換)你的電話號碼轉換成字符串時,它就會被打印出來。
>>> a = 1
>>> b = 10
>>> print("my number is {} and his number is {}".format(a, b))
my number is 1 and his number is 10
What we are doing is substituting the symbol {} in the print statement in the string we want to display in the exact place we want the number to go, and use the .format() to pass variables to the {} that appear in order. What happens is the variables a and b get converted into strings automatically and injected into our print statement cleanly. You can do this with floats, lists, dictionaries, or anything else you want to display.
There are a number of different formatting options if you want to get specific about how many decimal points to display, etc., but that is out of the scope of this exercise. If you want to read more about string formatting in Python, you can read about it on this helpful website that goes into a great amount of detail.
我們正在做的是將{}要顯示的字符串中的符號替換為打印語句中要顯示的數字的確切位置,然後使用.format()將變量傳遞給{}按順序出現的。發生的事情是變量,a並b自動將其轉換為字符串並print乾淨地註入到我們的語句中。您可以使用浮點數,列表,字典或其他任何想要顯示的內容來執行此操作。
如果要具體說明要顯示的小數點數等,可以使用多種格式設置選項,但這不在本練習的範圍之內。如果您想了解有關Python中字符串格式的更多信息,可以在這個非常有用的網站上詳細了解它。
MORE ON DICTIONARY KEYS 有關字典鍵的更多信息 <<
Previous Next >> Solutions 解決方案