Python小贴士

原文请点击这里

持续更新

1、字符串

upper()、lower()大小写转换

str = "TEST LOWER()"
str1 = "test upper()"
print(str.lower())
print(str1.upper())

#test lower()
#TEST UPPER()

split()

Python split()通过指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串.

#!/usr/bin/python

str = "Line1-abcdef \nLine2-abc \nLine4-abcd"
print str.split( )
print str.split(' ', 1 )
#['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
#['Line1-abcdef', '\nLine2-abc \nLine4-abcd']

replace()

replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。没有查找到需要替换的字符串则保持不变。

#!/usr/bin/python

str = "this is string example....wow!!! this is really string"
print str.replace("is", "was")
print str.replace("is", "was", 3)

#thwas was string example....wow!!! thwas was really string
#thwas was string example....wow!!! thwas is really string

2、List

reverse()

reverse() 函数用于反向列表中元素。

#!/usr/bin/python

aList = [123, 'xyz', 'zara', 'abc', 'xyz']

aList.reverse()
print "List : " ,aList

#List: ['xyz', 'abc', 'zara', 'xyz', 123]

insert()、append()

#!/usr/bin/python

aList = [123, 'xyz', 'zara', 'abc']

aList.insert( 3, 2009)
aList.append( 2008)

print "Final List : %s" % aList

#Final List : [123, 'xyz', 'zara', 2009, 'abc',2008]

3、字典

update()

Python 字典(Dictionary) update() 函数把字典dict2的键/值对更新到dict里。

#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7}
dict2 = {'Sex': 'female' }

dict.update(dict2)
print "Value : %s" %  dict

#Value : {'Age': 7, 'Name': 'Zara', 'Sex': 'female'}

你可能感兴趣的:(Python小贴士)