变量

变量名只能包含字母、数字和下划线,且只能以字母或下划线打头。
应使用小写的 Python 变量名。虽然在变量名中使用大写字母不会导致错误,但是大写字母在变量名中有特殊含义。(Todo: 什么含义?)

字符串

  1. name = "ada aBc"
  2. # 每个单词的首字母大写,其余字母小写
  3. print(name.title()) # Ada Abc
  4. # 全大写
  5. print(name.upper()) # ADA ABC
  6. # 全小写
  7. print(name.lower()) # ada abc

在字符串中使用变量

f 字符串:在字符串前引号前加上字母 f,再将要插入的变量放在花括号内。

  1. first_name = "ada"
  2. last_name = "lovelace"
  3. full_name = f"{first_name} {last_name}"
  4. print(full_name) # ada lovelace
  5. print(f"hello {full_name.title()}") # hello Ada Lovelace

使用制表符和换行符来添加空白

制表符 \t
换行符 \n

删除空白

rstrip 删除字符串末尾空白
lstrip 删除字符串开头空白
strip 删除字符串两边空白

浮点数

任意两个数相除时,结果总是浮点数,即使两个数都是整数且能整除。

无论哪种运算,只要有操作数是浮点数,结果总是浮点数。

数中的下划线

可以使用下划线将数字分组,是其更清晰易读,打印和存储时会忽略下划线,1000 和 1_000、10_00 没什么不同。
整数和浮点数都适用,但只有 Python 3.6 及其以上才支持。

  1. num = 100_0
  2. print(num) # 1000
  3. print(1_000 == 100_0) # True

同时给多个变量赋值

用逗号将变量名分开,对于要赋给变量的值也用逗号分开。Python 将按顺序将每个值赋给对应的变量,变量名和值的个数要一致,不一致时会报错。

  1. x,y,z = 1, 2, 3
  2. print(x, y, z) # 1, 2, 3

Python 之禅

执行 import this

  1. The Zen of Python, by Tim Peters
  2. Beautiful is better than ugly.
  3. Explicit is better than implicit.
  4. Simple is better than complex.
  5. Complex is better than complicated.
  6. Flat is better than nested.
  7. Sparse is better than dense.
  8. Readability counts.
  9. Special cases aren't special enough to break the rules.
  10. Although practicality beats purity.
  11. Errors should never pass silently.
  12. Unless explicitly silenced.
  13. In the face of ambiguity, refuse the temptation to guess.
  14. There should be one-- and preferably only one --obvious way to do it.
  15. Although that way may not be obvious at first unless you're Dutch.
  16. Now is better than never.
  17. Although never is often better than *right* now.
  18. If the implementation is hard to explain, it's a bad idea.
  19. If the implementation is easy to explain, it may be a good idea.
  20. Namespaces are one honking great idea -- let's do more of those!