python的字符串操作

字符串最基础的操作:

拼接

总共三种方法:

  • 1、最简单的,加号连接
string = 'hello '+'world! '

不过据说这种方法效率低……
不过我感觉做大的缺点是不能和运算相连接

  • 2、用join链接
strList = ['hello ', 'world! '] 
str = ''.join(strList)
  • 3、最好的方法,占位符替换
str = '%s%s' % ('hello' , 'world! ')

这是一种格式化的方法,功能最强大,最规整。推荐使用。而且数字是可以直接参与替换的,e.g:

str = r"hello world%s! " % (1)
print str

结果是

hello world1! 

截取

  • 1、通过位置序号截取。

大家都知道python有两种序号方式,一个是从左往右序号从0开始,依次加1;
另一种是从右往左从-1开始,依次减1。
正序:

str = r"hello world%s! " % (1)
print str[0:5]

结果:

hello

倒序:

str = r"hello world%s! " % (1)
print str[-8:-1]

结果:

world1!
  • 2、通过特殊符号截取

两步走,第一步找到特殊符号的位置(方法参照查找),第二部使用上述方法截取。

查找

查找到某个字符的位置

  • 1、find函数
str = r"hello world! "
a = str.find(' ')#查找单个字符
print a
b = str.find('ld')#查找字符串
print b

结果:

5
9
  • 2、index函数
str = r"hello world! "
a = str.index('ld')
print a

结果:

9

index区别于find的一点是,如果没有查到,会返回-1

分割

用某个特殊字符分割字符串,得到一个list

str = r"hello world! "
a = str.split(' ')
print a

结果:

['hello', 'world!', '']

大小写转换

大写:upper()函数
小写:lower()函数
首拼大写:capitalize()函数
是否大写:isupper() 函数
是否小写: islower()函数
是否首拼大写:istitle()函数

str = r"hello world! "
a = str.upper()
print a

结果:

HELLO WORLD! 

猜你喜欢

转载自blog.csdn.net/king_john/article/details/78134144