Python Strings筆記

1 %

>>> '%-*s' % (10, 'hello')
'hello     '
>>> '%*s' % (10, 'hello')
'     hello'
- 代表左對齊
*後面括號中有數字,代表長度  

2 不言而喻

append()
len()

3 find()

find(sub[, start[, end]]) 返回最先找到的sub的索引,若查找失敗則返回-1

4 replace()

S.replace(old, new [, count]) -> string

5 split() rsplit()

str.split([sep [,maxsplit]]) -> list of strings

>>> line = '1,2,3,4,5,6'
>>> line.split(',')
['1', '2', '3', '4', '5', '6']
>>> line.split(',', 4)
['1', '2', '3', '4', '5,6']
>>> line.rsplit(',', 4)
['1,2', '3', '4', '5', '6']

6 strip rstrip lstrip

str.strip() #Return a copy of the string S with leading and trailing whitespace removed.
rstrip() #Return a copy of the string S with trailing whitespace removed.
lstrip() #Return a copy of the string S with leading whitespace removed.

7 center() ljust() rjust()

center(...)
    S.center(width[, fillchar]) -> str

>>> s.ljust(10, 'x')
'1.2xxxxxxx'
>>> s.rjust(10, 'x')
'xxxxxxx1.2'
>>> s.center(10, 'x')
'xxx1.2xxxx'

8 partition() rpartition()

rpartition(...)
    S.rpartition(sep) -> (head, sep, tail)
    
    Search for the separator sep in S, starting at the end of S, and return
    the part before it, the separator itself, and the part after it.  If the
    separator is not found, return two empty strings and S.

>>> str = 'hello world'
>>> str.rpartition(' ') 
('hello', ' ', 'world')
>>> str.partition(' ')
('hello', ' ', 'world')
>>> str.rpartition('l')  #只分一次
('hello wor', 'l', 'd')
>>> str.partition('l') #返回tuple,並且顯示分隔的sep
('he', 'l', 'lo world')
>>> str.split(' ') #返回 list
['hello', 'world']

9 isdigit() isnumeric()

好像沒有什麼區別?

isdigit(...)
    S.isdigit() -> bool
    
    Return True if all characters in S are digits
    and there is at least one character in S, False otherwise
isnumeric(...)
    S.isnumeric() -> bool
    
    Return True if there are only numeric characters in S,
    False otherwise.
    

10 swapcase()

#返回大小寫相互轉化的結果
>>> line = 'HellO WOrld'
>>> line.swapcase()
'hELLo woRLD'

11 zfill()

#字符串左邊填充0
>>> line.zfill(15)
'0000HellO WOrld'   

12 expandtabs()

S.expandtabs([tabsize]) -> str
The default tabsize is 8.
>>> line
'a\tb\tc'
>>> line.expandtabs()
'a       b       c'

13 isalpha isdigit isalnum islower isspace istitle isupper istitle title capitalize

並沒有iscapitalize函數,不過可以自己實現:

def iscapitalize(s):
   return s == s.capitalize()
>>> a = 'hello world'
>>> a.capitalize()
'Hello world'
>>> a.title()
'Hello World'
>>> a  = 'Hello world'
>>> a.istitle()
False
>>> a  = 'Hello World'
>>> a.istitle()
True

14 maketrans translate

3.X中實現:

>>> map = str.maketrans('he', 'sh')
>>> str.translate(map)
'shllo world'
>>> str
'hello world'

2.X中下面的方法可靠,但在3.X中不行

string.maketrans(from, to) #from to must have the same length.
string.translate(s, table[, deletechars])
str.translate(table[, deletechars])
unicode.translate(table)
>>> import string
>>> map = string.maketrans('123', 'abc')
>>> s = '2341321234232123'
>>> s.translate(map)
'bc4acbabc4bcbabc'
import string 
def translator(frm='', to='', delete='', keep=None): 
if len(to) == 1: 
        to = to * len(frm) 
    trans = string.maketrans(frm, to) 
    if keep is not None: 
        allchars = string.maketrans('', '') 
        delete = allchars.translate(allchars, keep.translate(allchars,delete))
    def translate(s): 
        return s.translate(trans, delete) 
    return translate

15 format()

15.1 基本格式

{fieldname ! conversionflag : formatspec}
fieldname: number(a potitional argument) or keyword(named keyword argument)
                   .name or [index]
                   "Weight in tons {0.weight}"
                   "Units destroyed: {players[1]}"
conversionflag: s r a ==>str repr ascii
formatspec: [[fill]align[sign] [#] [0] [width] [.percision] [typecode]]
                     fill ==> 除{} 外的所有字符都可以
                     align==>    > < = ^
                     sign ==> '+' '-' ' '
                                      '-' 爲默認情況 正數不顯示+負數顯示-
                                      '+'表正負數都顯示符號
                                      'space' 表示數字前面顯示一空格
                     width precision ==> integer
                     type ==>  b c d e E f F g G n o   

15.2 Accessing arguments by potition:

>>> print '{0} {1} {2}'.format('a', 'b', 'c')
a b c
>>> '{2}, {1}, {0}'.format(*'abc')   ### *
'c, b, a'

>>> 'My {1[spam]} runs {0.platform}'.format(sys, {'spam': 'laptop'})
'My laptop runs linux2'

15.3 Accessing arguments by name:

>>> 'Coordinates: {latitude}, {longtitude}'.format(latitude = '23.2N', longtitude = '-112.32W')
'Coordinates: 23.2N, -112.32W'

>>> coord = {'latitude': '23.12N', 'longtitude': '-23.23W'}
>>> 'Coordinates: {latitude}, {longtitude}'.format(**coord)
'Coordinates: 23.12N, -23.23W'

>>> print '{name} {age}'.format(age=12, name='admin')
admin 12

>>> 'My {config[spam]} runs {sys.platform}'.format(sys=sys, config={'spam': 'laptop'})
'My laptop runs linux2'

15.4 Accessing arguments' attributes:

>>> c = 3 -5j
>>> 'The complex number {0} is formed from the real part {0.real} and the imaginary part {0.imag}'.format(c)
'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0'

15.5 Accessing argument's items:

>>> coord = (3, 5)
>>> 'X: {0[0]}; Y: 0[1]'.format(coord)
'X: 3; Y: 0[1]'
>>> print '{array[2]}'.format(array=range(10))
2

15.6 !s !r

>>> "repr() show quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
"repr() show quotes: 'test1'; str() doesn't: test2"

15.7 Aligning the text and specifying a width

>>> '{: <30}'.format('left aligned')
'left aligned                  '
>>> '{: >30}'.format('right aligned')
'                 right aligned'
>>> '{: ^30}'.format('centered')
'           centered           '
>>> '{:*^30}'.format('centered')
'***********centered***********'

15.8 +f -f

>>> '{:-f}; {:-f}'.format(3.14, -3.14)
'3.140000; -3.140000'
>>> '{:+f}; {:+f}'.format(3.14, -3.14) 
'+3.140000; -3.140000'
>>> '{:f}; {:f}'.format(3.14, -3.14)
'3.140000; -3.140000'

15.9 b o x

>>> 'int: {0: d}; hex: {0: x}; oct: {0: o}; bin{0: b}'.format(42)
'int:  42; hex:  2a; oct:  52; bin 101010'
# # with 0x, 0o, or 0b as prefix:
>>> 'int: {0: d}; hex: {0: #x}; oct: {0: #o}; bin{0: #b}'.format(42)
'int:  42; hex:  0x2a; oct:  0o52; bin 0b101010'

15.10 Using , as a thousand seperator

>>> '{: ,}'.format(12345678)
' 12,345,678'

15.11 More==>Refer to doc-pdf(Python 參考手冊)-library.pdf–>String services.

>>> print '{attr.__class__}'.format(attr=0)
<type 'int'>

Author: visaya <[email protected]>

Date: 2011-08-01 19:12:35 CST

HTML generated by org-mode 6.33x in emacs 23


點擊打開鏈接

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章