Python Basics: Working with Strings

本文介绍了Python中格式化字符串的方法,包括使用format函数和f-string的方式。通过具体示例展示了如何利用索引和关键字参数来格式化输出,以及如何指定浮点数的格式。

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 pi
	In [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 e
	In [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.  








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值