字符串操作

2018-12-09  本文已影响0人  鲸随浪起

字符串常见操作

mystr = 'hello world itcast and itcastcpp'

find

检测查询是否包含在mystr中,如果有返索引值,否则返回-1

rfind

从右侧查找

index

检测查询内容是否包含在mystr中,如果有返回索引值,否则报错

rindex

从右侧查找

count

检测查询内容在mystr中出现的次数


Snip20160814_218.png

replace

把mystr中的内容替换成其他内容


Snip20160814_214.png

split

以分隔符切片,列表返回
mystr.split(' ') #以空格分割
['hello','world','itcast','and','itcastcpp']
mystr.salit(' ',2) #前两个分割
['hello', 'world', 'itcast and itcastcpp']

Snip20160814_211.png

capitalize

把字符串的第一个字符大写

title

把字符串的每个单词首字母大写

startswith

检查字符串是否为hello开头,是返回True,不是返回False

endswith

检查字符串是否以cpp结束,是返回True,不是返回False


Snip20160814_221.png

lower

所有大写转小写
mystr.lower()

upper

所有小写转大写

ljust

原字符串左对齐,并使用空格填充width的长度
mystr.ljust(10) #右侧10个空格填充长度

rjust

原字符串右对齐,并使用空格填充width的长度
mystr.rjust(10) #左侧10个空格填充长度

center

字符串居中,左右使用空格填充width的长度
mystr.center(10)

lstrip

删除左边空白字符

rstrip

删除右边空白字符

strip

删除左右空白字符

partition

搜索itcast把字符串分割成三部分,itcast前,itcast,itcast后,返回元组
mystr.partition("itcast")
('hello world','itcast','and itcastcpp')

rpartition

从右边开始,返回元组
mystr.partition("itcast")
('hello world itcast and ','itcast','cpp')

splitlines

按照行分割,按照\n分割成列表

isalpha

如果都是字母,空格除外,返回True,否则False

isdigit

如果都是数字,返回True,否则False

isalnum

如果都是字母和数字,返回True,否则False

isspace

如果都是空格,返回True,否则False

join

指定字符连接序列中元素生成新的字符串


join使用
上一篇 下一篇

猜你喜欢

热点阅读