python的几个有趣点

1、变量 “_”

交互模式中,最近一个表达式的值赋给变量 _ 。这样我们就可以把它当作一个桌面计算器,很方便的用于连续计算,例如:

>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06

此变量对于用户是只读的。不要尝试给它赋值 —— 你只会创建一个独立的同名局部变量,它屏蔽了系统内置变量的魔术效果.


2、三引号

字符串可以标识在一对儿三引号中: `"""``'''` 。三引号中,不需要行属转义,它们已经包含在字符串中。

print("""\
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
""")

得到如下输出:

Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to

3、原始字符串

如果我们生成一个“原始”字符串, \n 序列不会被转义,而且行尾的反斜杠,源码中的换行符,都成为字符串中的一部分数据,因此下例:

hello = r"This is a rather long string containing\n\
several lines of text much as you would do in C."

print(hello)

会打印:

This is a rather long string containing\n\
several lines of text much as you would do in C.

4、字符串的“ + ”和" * "

字符串可以由 + 操作符连接(粘到一起),可以由 * 重复:

>>> word = 'Help' + 'A'
>>> word
'HelpA'
>>> '<' + word*5 + '>'
'<HelpAHelpAHelpAHelpAHelpA>'



原文地址:https://www.cnblogs.com/javawebsoa/p/3091373.html