1. 程式人生 > 實用技巧 >python-資料清洗與編碼解碼

python-資料清洗與編碼解碼

0x01 join

str = 'hk$$yicunyiye$$hello world'
print(str.split('$$'))

#自己實現
result = ''
for i in str.split('$$'):
    result += i+' '
print(result)

#內建函式
print(','.join(str.split('$$')))

輸出

['hk', 'yicunyiye', 'hello world']
hk yicunyiye hello world
hk,yicunyiye,hello world

0x02 endswith

str = ['a.py','b.exe','c.e','d.erl']
for s in str:
    if  s.endswith('.py'):
        print(s)

輸出a.py

0x03 startswith

str = ['a.py','b.exe','c.e','d.erl']
for s in str:
    if  s.startswith('a'):
        print(s)

輸出a.py

0x04 多重替換maketrans和translate

intab = 'aeiou'
outtab = '12345'

trantab = str.maketrans(intab,outtab)
result = "this is string example...wow!!"
print(result.translate(trantab))

輸出

th3s 3s str3ng 2x1mpl2...w4w!!

0x05 replace單次替換

#單次替換
print(result.replace('i','1').replace('e','2'))

輸出

th1s 1s str1ng 2xampl2...wow!!

0x06 strip(去掉空格)

string = '    yicunyiye    '
print(string.strip())
//類似於
print(string.lstrip())
print(string.rstrip())

0x07 format 和 f'

name='yicunyiye'
age=20
string = 'name is {}; age is {};'.format(name,age)
print(string)

and

name='yicunyiye'
age=20
string = f'name is {name}; age is {age};'
print(string)

輸出

name is yicunyiye; age is 20;