zl程序教程

您现在的位置是:首页 >  后端

当前栏目

python字符串的常见操作-小结

Python 操作 字符串 常见 小结
2023-09-14 08:59:04 时间

字符串常见操作

mystr = “hello world itcast and itcastcpp”

(1) 、find

检测str中是否包含在mystr中,如果是,返回开始的索引值,否则返回-1

mystr.find('itcast')
12
mystr.find('itcast', 13, 100)      # 从下标13开始查找。查找100个长度。
23
mystr.find('itcast', 13)           # 从下标13开始查找。
23
mystr.find('abc')
-1

(2)、index

跟find()方法一样,只不过如果str不在 mystr中会报一个异常.

mystr.index('it')
12
mystr.index('it', 13)
23
mystr.index('it', 13, 100)
23
mystr.index('ita')
报错

(3)、count

返回字符出现的次数。

mystr.count('it')
2
mystr.count('it',13)     # 从下标13位置开始查找。
1
mystr.count('it',13, 4)  # 从下标13开始查找。查找4个长度。
0
mystr.count('ita')
0

(4)、replace

替换字符串。不改变原来mystr,而是形成新的字符串。

mystr.replace('it', '123')          # 将mystr中的所有it变成123
'hello world 123cast and 123castcpp'
mystr.replace(' ', '', 2)           # 将mystr中的空格变成,只变前两处。
'helloworlditcast and itcastcpp'

(5)、split

分割字符串。不改变原来mystr,而是形成新的列表。

mystr.split()           # 和mystr.split(‘ ’)效果一样
['hello', 'world', 'itcast', 'and', 'itcastcpp']
# 括号里什么都不加,认为是按照看不见字符(空格、\n、\t)进行切割。

mystr.split(' ', 2)     # 分割2次,形成2+1=3块。
['hello', 'world', 'itcast and itcastcpp']

(6)、capitalize

把字符串的第一个字符大写。整个字符串只有第一个单词大写。不改变原来mystr,而是形成新的字符串。

a = 'heLLo WoRLD'
a.capitalize()
'Hello world'

(7)、title

把字符串的每个单词首字母大写。不改变原来mystr,而是形成新的字符串。

a.title()
'Hello World'

(8)、startswith

检查字符串是否是以 obj 开头, 是则返回 True,否则返回 False。不改变原来mystr,而是形成新的字符串。

a.startswith('he')
True
a.startswith(‘__’)

(9)、endswith

检查字符串是否以obj结束,如果是返回True,否则返回 False.不改变原来mystr,而是形成新的字符串。

(10)、lower

转换 mystr 中所有大写字母为小写。不改变原来mystr,而是形成新的字符串。

mystr.lower()

(11)、upper

转换 mystr 中所有小写字母为大写。不改变原来mystr,而是形成新的字符串。

mystr.upper() 

(12)、ljust

返回一个原字符串左对齐,并使用空格填充至长度 width 的新字符串。不改变原来mystr,而是形成新的字符串。

a.ljust(20)
'heLLo WorlRD        '

(13)、rjust

返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串。不改变原来mystr,而是形成新的字符串。

a.rjust(20)
'        heLLo WorlRD'

(14)、center

返回一个原字符串居中,并使用空格填充至长度 width 的新字符串。

a.center(20)
'    heLLo WorlRD    '

(15)、lstrip

删除 mystr 左边的空白字符

(16)、rstrip

删除 mystr 右边的空白字符

(17)、strip

删除mystr字符串两端的空白字符。不改变原字符串。

b.strip()
# 去掉b字符串左右两侧的看不见的字符(如:空格、换行)

(18)、rfind

mystr.rfind(“itcast”)
# 从右边开始找。

(19)、rindex

类似于 index(),不过是从右边开始。

(20)、partition

把字符串3份

# 把mystr以str分割成三部分,str前,str和str后。原字符串不变,生成新元组。
mystr.partition(' ')
('hello', ' ', 'world itcast and itcastcpp')

(21)、rpartition

类似于 partition()函数,不过是从右边开始。原字符串不变,生成新元组。

mystr.rpartition(' ')
('hello world itcast and', ' ', 'itcastcpp')

(22)、splitlines

按照行分隔,返回一个包含各行作为元素的列表。原字符串不变,生成新的列表。

b=”hello\nworld”
b.splitlines()
['hello', 'world']

(23)、isalpha

判断是否是字母

mystr.isalpha()
True

(24)、isdigit

判断是否都是数字

mystr.isdigit()
False

(25)、isalnum

判断是否只有字母或者数字

“aaa123”.isalnum()
True

(26)、isspace

是否是空白字符,看不到的字符

“\n   ”.isspace()
True

(27)、join

d=[‘aa’, ‘bb’, ‘cc’, ‘dd’]
“”.join(d)
# 输出
aabbccdd