Python字符串和列表的内置方法

一.字符串内置方法

1.strip()  删除开头和结尾的字符串

s.strip(rm) 删除s字符串中开头,结尾处,位于rm删除序列的字符串

s.lstrip(rm) 删除s字符串中开头位于rm删除序列的字符串

s.rstrip(rm) 删除s字符串中结尾处,位于rm删除序列的字符串

1.当括号中为空时,默认删除空白符(包括' ',' ',' ',' ')

In [1]: i = '  134  34  '
In [2]: print(i.strip())
134  34

2.这里的rm删除序列是只要边(开头或结尾)上的字符在删除序列内,就删除掉。

In [4]: i = 123321
In [5]: print(i.strip('12'))
343

2.split() 将字符串分割为列表

s.split('.') 将s字符串以为.为分割符号,分割为列表.

>>> a = '	adb	d	ade	'
>>> print(a)
    adb    d    ade
>>> print(a.split())
['adb', 'd', 'ade']

1.按某一个字符分割,如‘.’

>>> a = 'wwww.baidu.com'
>>> print(a)
wwww.baidu.com
>>> print(a.split('.'))
['wwww', 'baidu', 'com']

2.按某一个字符分割,且分割n次。如按‘.’分割1次

a = 'wwww.baidu.com'
>>> print(a)
wwww.baidu.com
print(a.split('.',1))
['wwww', 'baidu.com']

3.按某一字符(或字符串)分割,且分割n次,并将分割的完成的字符串(或字符)赋给新的(n+1)个变量。

>>> url = ('www.baidu.com')
>>> str1,str2 = url.split('.',1)
>>> print(str1)
www
>>> print(str2)
baidu.com

 3.lower,upper 大小写转化

>>> print('hello'.upper())
HELLO
>>> print('WORLD'.lower())
world

4.startswith,endwith 检验开头结尾

>>> name='alex_SB'
>>> print(name.endswith('SB'))
True
>>> print(name.startswith('alex'))
True

5.form 格式化字符串

res='{} {} {}'.format('zhangshan',18,'male')
res='{1} {0} {1}'.format('zhangshan',18,'male')
res='{name} {age} {sex}'.format(sex='male',name='zhangshann',age=18)

6.join 将列表合并为字符串

>>> tag= ''
>>> print(tag.join(['et','say','hello','world']))
etsayhelloworld

7.replace 替换

>>> name='alex say :i have one tesla,my name is alex'
>>> print(name.replace('alex','SB',1))
SB say :i have one tesla,my name is alex

二.列表

1.切片

#ps:反向步长
l=[1,2,3,4,5,6]

#正向步长
l[0:3:1] #[1, 2, 3]
#反向步长
l[2::-1] #[3, 2, 1]
#列表翻转
l[::-1] #[6, 5, 4, 3, 2, 1]

2.appen追加

>>> li = [1,2,3,4]
>>> li.append(5)
>>> print(li)
[1, 2, 3, 4, 5]
>>> li.append([6,7,8])
>>> print(li)
[1, 2, 3, 4, 5, [6, 7, 8]]

3.pop弹出

>>> print(li)
[1, 2, 3, 4, 5, [6, 7, 8]]
>>> li.pop(0)
1
>>> li
[2, 3, 4, 5, [6, 7, 8]]

li=['a','b','c','d']

按照元素值去单纯地删除某个元素

del li[1]

res=li.remove('c')

原文地址:https://www.cnblogs.com/gongcheng-/p/9636055.html