1.Python部分實用操作


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

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 4. 流程控制語句 除了 while 語句,Python還擁有在其他語言里常見的控制語句,以及一些好玩的語句。 4...
    慧琴如翌閱讀 544評論 0 0
  • 基礎語法 運行 Python 交互式解釋器 在命令行窗口執行python后,進入 Python 的交互式解釋器。 ...
    小天真_5eeb閱讀 1,422評論 0 36
  • 我是黑夜里大雨紛飛的人啊 1 “又到一年六月,有人笑有人哭,有人歡樂有人憂愁,有人驚喜有人失落,有的覺得收獲滿滿有...
    陌忘宇閱讀 8,592評論 28 53
  • 信任包括信任自己和信任他人 很多時候,很多事情,失敗、遺憾、錯過,源于不自信,不信任他人 覺得自己做不成,別人做不...
    吳氵晃閱讀 6,222評論 4 8
  • 步驟:發微博01-導航欄內容 -> 發微博02-自定義TextView -> 發微博03-完善TextView和...
    dibadalu閱讀 3,167評論 1 3