【Python】string/list/integer常用函數總結


 

 

 

1 3.X中print()

在python3.2:
print(value, ..., sep=' ', end='\n', file=sys.stdout)
sep表示輸出之間的符號,end表示整個輸出的結束符。

>>> print('hello', 'world')
hello world
>>> print('hello', 'world', sep='\n')
hello  #Because sep is \n, this is a new line.
world
>>> print('hello', 'world', end=' ')
hello world >>>  #Because end is ' ', so this is no newline.

2 strings:

 

2.1 %

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

2.2 不言而喻

append()
len()

2.3 find()

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

2.4 replace()

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

2.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']

2.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.

2.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'

2.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']

2.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.
    

2.10 swapcase()

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

2.11 zfill()

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

2.12 expandtabs()

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

2.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

2.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

2.15 format()

 

2.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   

2.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'

2.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'

2.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'

2.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

2.15.6 !s !r

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

2.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***********'

2.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'

2.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'

2.15.10 Using , as a thousand seperator

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

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

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

3 lists:

 

3.1 list()

 

3.2 reverse()

 

3.3 sort() sorted()

sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;

區別在:sorted是built-in 函數, sort是list的成員函數。前者作用於列表但並不對列表造成影響,后才修改了列表。

iterable 可迭代的類葯
cmp 比較函數
key 用列表元素的某個屬性和函數進行作為關鍵字
reverse 排序規則
一般cmp,key 可以用lambda表達式,效率key>cmp

>>>L = [('b',2),('a',1),('c',3),('d',4)]
>>>print sorted(L, cmp=lambda x,y:cmp(x[1],y[1]))
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]

>>>L = [('b',2),('a',1),('c',3),('d',4)]
>>>print sorted(L, key=lambda x:x[1]))
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]

>>> print sorted([5, 2, 3, 1, 4], reverse=True)
[5, 4, 3, 2, 1]
>>> print sorted([5, 2, 3, 1, 4], reverse=False)
[1, 2, 3, 4, 5]

3.4 insert()

L.insert(index, object)   # Insert object before index

3.5 pop([index])

L.pop([index]) # Remove and return item at index (defaut last)

3.6 remove(value)

L.remove(value)   # Remove fist occurence of value.

3.7 count(value)

L.count(value) # Return number of occurrences of value.

3.8

 

4 integers:

 

4.1 ord()

ord('字符') #返回ASCII碼

Author: visaya <visayafan@gmail.com>

Date: 2011-08-01 19:02:09 CST

HTML generated by org-mode 6.33x in emacs 23


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM