Python Basics: Working with Strings

来源:互联网 发布:淘宝自动装修软件 编辑:程序博客网 时间:2024/05/21 20:28

The format String method

When writing new code, the mechanism of choice is the format string method, which combines and extends the strong points of the earlier methods. Each replacement field is enclosed in curly brackets and may include a name, as well as information on how to convert and format the value supplied for that field.

The simplest case is where the fields have no name, or where each name is just an index.

In [1]:"{}, {} and {}".format("first", "second", "third")
Out[1]: 'first, second and third'
The indices need not be in order like this, though.

In [3]:"{3} {0} {2} {1} {3} {0}".format("be","not","or","to")Out[3]: 'to be or not to be'
Named fileds work just as expected.

In [4]:from math import piIn [5]"{name} is equal to {value:.2f}".format(name="π",value=pi)Out[5]: 'π is equal to 3.14'
The ordering of the keyword arguments does not matter, of course. In this case, I have also supplied a format specifier of .2f, separated from the field name by a colon, meaning we want float-formatting with three decimals. Without the specified, the result would be as follows:

In [5]: "{name} is equal to {value}".format(name="π",value=pi)Out[6]: 'π is equal to 3.141592653589793'
Finally, in Python 3.6, there’s a shortcut you can use if you have variables named identically to corresponding replacement fields. In that case, you can use so-called f-strings, written with the prefix f.

In [7]: from math import eIn [8]: f"Euler's constant is equal to {e}"Out[8]: "Euler's constant is equal to 2.718281828459045"
Here, the replacement field named e simply extracts the value of the variable of the same name, as the string is being constructed. This is equivalent to the following, slightly more explicit expression:

In [10]: "Euler's constant is roughly {e}.".format(e=e)Out[10]: "Euler's constant is roughly 2.718281828459045."
I plan to write some blogs about python and deep learning to record my learning process. I am going back to my dorm, that's all for today.  







阅读全文
0 0
原创粉丝点击