Python 基礎(二)
阿新 • • 發佈:2018-11-16
11. 擷取字串的某部分
使用切片[:]
>>> s = 'abcdefg'
>>> s[1:5]
'bcde'
>>> s[:5]
'abcde'
>>> s[5:]
'fg'
>>> s[-3:]
'efg'
>>> s[1:5:2]
'bd'
注意:
- 字元始於0
- 字符集不包含右邊的端點,故字母
f
不包含
切片功能異常強大,感興趣者可另往查閱相關資料
12. 用一個字串替換另一個字串的某部分
使用replace
函式
>> > s = 'My name is Waao'
>>> s.replace('Waao','Jack')
'My name is Jack'
13. 將一個字串轉換為全部大寫或全部小寫
使用upper
或lower
函式
>>> 'Abc'.upper()
'ABC'
>>> 'Abc'.lower()
'abc'
>>> s = 'abc'
>>> s.upper()
'ABC'
>>> print(s)
abc
和大多數處理字串的方式一樣,upper
和lower
14. 有條件地執行命令
if
語句
>>> x = 100
>>>if x < 200:
... print('OK')
...elif x < 250:
... print('NOT')
...else:
... print('NONE')
...
OK
15. 比較值
小於 | < |
大於 | > |
小於等於 | <= |
大於等於 | >= |
等於 | == |
不等於 | != 或 <> |
16. 邏輯運算子
與 | and |
或 | or |
非 | not |
17. 重複執行指令指定的次數
>>> for i in range(1,4):
... print(i)
...
1
2
3
range(x,y)
會生成從x
到y
的列表,故執行次數為y-x
次
18. 重複執行指令,直到某些條件變化
使用while
語句,用法與C語言相似
>>> answer = ' '
>>> while answer != 'X':
... answer = input('Enter command:')
...
Enter command:A
Enter command:B
Enter command:X
19. 中斷迴圈
可使用break
退出while
或for
迴圈
>>> while True:
... answer = input('Enter command:')
... if answer == 'X':
... break
20. 在Python 中定義函式並呼叫
函式的命名約定:與變數命名約定相同,名稱應當以一個小寫字母開頭,若名稱中包含多個單詞,單詞之間應當以下劃線分隔
函式可指定預設值n=2
>>> def count_to_n(n=2):
... for i in range(1,n):
... print(i)
...
>>> count_to_n(3)
1
2
3
>>> count_to_n()
1
2
若函式需要返回值,則使用return
>>> def a_sentence(s):
... return s + ' is me.'
...
>>> print(a_sentence(Waao))
Waao is me.