还是在今天看的内容中,选一点值得记一笔的。

  • Python中,格式化字符串另有一种方式:.format()方法。该方法从python2.6开始引入。这种方法可以类比C中的printf:一个format string,一个参数列表。直接上例子:
print("{} {}".format("hello", "world"))
print("{0} {1}".format("hello", "world"))
print("{1} {0} {1}".format("hello", "world"))

对应输出:

hello world
hello world
world hello world

解读:如果{ }不加数字,那变量往{ }内“填空”的顺序就是依照format内从左到右。如果从0开始往{ }内填数字,那format从左到右列出的变量可以看作一个下标从0开始的一维数组,与format string标号的{ }对应。花括号之间留空格,否则会报错。花括号中间不要有多余的字符,如空格,否则也会报错。

  • print函数的end和sep。这是print函数里的可选参数。默认值分别是’\n’和’ ‘。end就是print完毕所有字符串后,接着打印的一个字符。sep就是输出字符串和“值”时,函数自动添加的分隔符。(还是习惯C++那种完全控制输出格式的感觉,讨厌这种自作聪明的设计……)
  • print有一种特别的写法,见代码:
print("ad" * 10)
print(5 * "*")

对应输出:

adadadadadadadadadad
*****
  • Python没有与C++完全对应的char类型。关于ASCII码的互转,Python里是对长度为1的字符串用chr()和ord()函数实现。
  • input函数:input函数可传递一个字符串,用于输入提示(即用户可输入区域之前打印的一条字符串)。input所得的值通过给一个变量赋值来接收。python3里,input返回的永远是字符串。如果需要其他类型变量,可以通过对input返回值进行强制转换实现功能。
  • pydoc:充当一个离线帮助。注意python3的帮助,用pydoc3命令获取。
  • python3里,函数的入栈顺序是从右往左。证明:运行以下代码,会首先要求输入一个值,之后打印位于参数列表第一位的字符串:
print("How old are you?", input())
  • Python的interactive mode中,输入import this并确认后,能得到一套python的编码规范。直接附在下面:

The Zen of Python
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren’t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one– and preferably only one –obvious way to do it.
Although that way may not be obvious at first unless you’re Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it’s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea — let’s do more of those!

Tim Peters
  • argv:准确的说,是下面这条命令:
from sys import argv

回忆一下C语言里的argc、argv参数。对,这个argv和C语言里的argv,包含的字串规则是完全一样的。只是如果想使用它,需要在加入argv模块后,如下这样做:

# Assume the shell command is "python3 demo.py dummy1 zummy2 fummy3"
x, y, z, w = argv
# After the above command executed, x is string "demo.py",
# y is string "dummy1", z and w share the same rule