標籤:python 字串 import 字母 拼接
字元寬度和精度:>>> from math import pi>>> ‘%10f‘%pi #欄位寬10‘ 3.141593‘>>> ‘%10.2f‘ %pi #欄位寬10,精度2‘ 3.14‘>>> ‘%.2f‘%pi #精度2‘3.14‘>>> ‘%.5s‘ %‘Guido van Rossum‘ #指定擷取字串的個數‘Guido‘>>> ‘%-10.2f‘ %pi #靠左對齊‘3.14 ‘>>> ‘%+10.2f‘ %pi #靠右對齊‘ +3.14‘find方法:返回字串所在位置的最左端索引>>> data = ‘With a moo-moo here, and a moo-moo there‘>>> data.find(‘moo‘)7join方法:將給定的字串按照指定的連結符號拼接在一起>>> dirs = [‘usr‘,‘bin‘,‘env‘]>>> ‘/‘.join(dirs)‘usr/bin/envlower方法:將大寫字母轉換為小寫字母>>> user = ‘Trondheim Hammer Dance‘>>> user.lower()‘trondheim hammer dance‘title方法:將字串轉換為標題>>> "that‘s all floks".title()"That‘S All Floks"replace方法:替換指定的字串,替換多個字元>>> data = ‘This is a test‘>>> data.replace(‘is‘,‘Jeff‘)‘ThJeff Jeff a testsplit方法:按照指定的分隔字元,分割字串>>> dirs = ‘/usr/sbin/env‘>>> dirs.split(‘/‘)[‘‘, ‘usr‘, ‘sbin‘, ‘env‘]strip方法:去除兩側(不包括內部)空格的字串>>> ‘ why what who when how ‘.strip()‘why what who when how‘translate方法:與replace方法一樣,只替換單個字元>>> from string import maketrans >>> table = maketrans(‘cs‘,‘kz‘)>>> table[97:123]‘abkdefghijklmnopqrztuvwxyz‘>>> maketrans(‘‘,‘‘)[97:123]‘abcdefghijklmnopqrstuvwxyz‘>>> ‘this is an incredible test‘.translate(table)‘thiz iz an inkredible tezt‘>>> ‘this is an incredible test‘.translate(table, ‘ ‘)#第二個參數為要刪除的字元‘thizizaninkredibletezt‘
本文出自 “馬行空” 部落格,謝絕轉載!
python學習筆記之字串(str)