python中常用的字符串操作



    Python主要的字符串操作包括复制、连接、比较、删除、查找、替换、分割等;本文将一一介绍:

1、复制

a='hello'
b=a
print(a,b)

输出结果:hello hello

2、连接或拼接

a='hello'
b='world'
print(a+b)

输出结果:hello world

3、比较

原来python2使用cmp(x, y)函数,此函数是比较x,y两个对象返回一个整数。x< y,返回值是负数 ,x>y 返回的值为正数。但是python3目前好像不再支持此函数了,根据文档说明,可以使用(x > y) - (x < y)代替cmp(x,y)

x='10'
y='8'
print((x > y) - (x < y))

输出结果:1

4、删除

删除函数主要有3个str.strip()、str.lstrip()、str.rstrip(),其分别为:
1)str.strip():删除字符串两边的指定字符,括号的写入指定字符,默认为空格
2)str.lstrip():删除字符串左边的指定字符,括号的写入指定字符,默认空格
3) str.rstrip():删除字符串右边的指定字符,括号的写入指定字符,默认空格
例如:

a='hello'
b=a.strip('o')
print(b)

输出结果:hell

5、查找

查找有两个函数:str.index 和str.find,但是本人使用最后一个。find()查找失败(没有查找的元素)会返回-1,不会影响程序运行。
例如:

a='hello'
b = a.find('l')
c = a.find('w')
print(b,c)

输出结果:2 -1

6、替换

a='hello'
a.replace("h","H")
print(a)

输出结果:Hello

7、分割

a='abcdefg'
b = a.split("e")
print(b)

输出结果:[‘abcd’, ‘fg’]