1. 取消 \
轉義
# 轉義
>>> print('C:\some\name') # here \n means newline!
C:\some
ame
# 取消轉義
>>> print(r'C:\some\name') # note the r before the quote
C:\some\name
2. 拆分長字符串
>>> text = ('Put several strings within parentheses '
... 'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'
>>>'Py' 'thon'
Python
這項功能只能用于兩個字面值,不能用于變量或表達式:
>>> prefix = 'Py'
>>> prefix 'thon' # can't concatenate a variable and a string literal
File "<stdin>", line 1
prefix 'thon'
^
SyntaxError: invalid syntax
3. 列表的淺拷貝
>>> squares = [1, 4, 9, 16, 25]
>>> squares[:]
[1, 4, 9, 16, 25]
4. 循環中的else
循環語句支持 else
子句;
for
循環中,可迭代對象中的元素全部循環完畢時
while
循環的條件為假時,執行該子句;
break
語句終止循環時,不執行該子句。 請看下面這個查找素數的循環示例:
>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(n, 'equals', x, '*', n//x)
# break后不會執行else
... break
... else:
... # loop fell through without finding a factor
... print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3