设为首页 收藏本站
查看: 921|回复: 0

[经验分享] 【Python】string/list/integer常用函数总结

[复制链接]

尚未签到

发表于 2015-4-27 09:08:45 | 显示全部楼层 |阅读模式
  
  







Table of Contents




  • 1 3.X中print()
  • 2 strings:

    • 2.1 %
    • 2.2 不言而喻
    • 2.3 find()
    • 2.4 replace()
    • 2.5 split() rsplit()
    • 2.6 strip rstrip lstrip
    • 2.7 center() ljust() rjust()
    • 2.8 partition() rpartition()
    • 2.9 isdigit() isnumeric()
    • 2.10 swapcase()
    • 2.11 zfill()
    • 2.12 expandtabs()
    • 2.13 isalpha isdigit isalnum islower isspace istitle isupper istitle title capitalize
    • 2.14 maketrans translate
    • 2.15 format()

      • 2.15.1 基本格式
      • 2.15.2 Accessing arguments by potition:
      • 2.15.3 Accessing arguments by name:
      • 2.15.4 Accessing arguments' attributes:
      • 2.15.5 Accessing argument's items:
      • 2.15.6 !s !r
      • 2.15.7 Aligning the text and specifying a width
      • 2.15.8 +f -f
      • 2.15.9 b o x
      • 2.15.10 Using , as a thousand seperator
      • 2.15.11 More==>Refer to doc-pdf(Python 参考手册)-library.pdf–>String services.




  • 3 lists:

    • 3.1 list()
    • 3.2 reverse()
    • 3.3 sort() sorted()
    • 3.4 insert()
    • 3.5 pop([index])
    • 3.6 remove(value)
    • 3.7 count(value)
    • 3.8


  • 4 integers:

    • 4.1 ord()





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('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)





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
Date: 2011-08-01 19:02:09 CST
HTML generated by org-mode 6.33x in emacs 23

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-61005-1-1.html 上篇帖子: Python实例应用 下篇帖子: 模拟登录新浪微博(Python)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表