1. 程式人生 > >廖雪峰python3複習總結——day4-1

廖雪峰python3複習總結——day4-1

高階特性

這一章主要是為了提高程式碼的開發效率。

切片:L[0:80:2]表示,從索引0開始取,直到索引3為止,每兩個元素取一個,支援-1索引。

     tuple和str 也可以切片。

L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']

>>> L[0:3]
['Michael', 'Sarah', 'Tracy']

>>> L[:3]
['Michael', 'Sarah', 'Tracy']

>>> L[-2:]
['Bob', 'Jack']
>>> L[-2:-1]
['Bob']

>>> L = list(range(100))
>>> L
[0, 1, 2, 3, ..., 99]
>>> L[::5]
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]

>>> (0, 1, 2, 3, 4, 5)[:3]
(0, 1, 2)

>>> 'ABCDEFG'[:3]
'ABC'
>>> 'ABCDEFG'[::2]
'ACEG'

練習:這裡是參考廖雪峰官網下面的答案的,本人編寫過於複雜。 

def trim(s):
    if s[:1] == ' ':
        return trim(s[1:])
    if s[-1:] == ' ':
        return trim(s[:-1])
    return s
或者
def trim(s):
    while s[:1]==' ':
        s=s[1:]
    while s[-1:]==' ':
        s=s[:-1]
    return s


# 測試:
if trim('hello  ') != 'hello':
    print('測試失敗!')
elif trim('  hello') != 'hello':
    print('測試失敗!')
elif trim('  hello  ') != 'hello':
    print('測試失敗!')
elif trim('  hello  world  ') != 'hello  world':
    print('測試失敗!')
elif trim('') != '':
    print('測試失敗!')
elif trim('    ') != '':
    print('測試失敗!')
else:
    print('測試成功!')