python常用内置函数可以操作字符串_python字符串常用内置方法

python字符串常用内置方法

定义:

字符串是一个有序的字符的集合,用与存储和表示基本的文本信息。

python中引号中间包含的就是字符串。

# s1='hello world'

# s2="hello world"

# s3="""hello world"""

# s3='''hello world'''

补充:

字符串的单引号和双引号都无法取消特殊字符的含义,如果想让引号内所有字符均取消特殊意义,在引号前面加r,如name=r'l\thf'

unicode字符串与r连用必需在r前面,如name=ur'l\thf'

#>>> print('a\nb')

a

b

#>>> print(r'a\nb')

a\nb

字符串连接

示例:

>>> x = 'hello world!'

>>> x = x[:6] + 'tom'

>>> x

'hello tom'

内置函数len()

len() 方法返回对象(字符串、列表、元组等)长度或项目个数。

语法:

len(s)

s-----对象

>>> str ='hello world'

>>> len(str)

11

>>> L = [1,2,3,4,5]

>>> len(L)

5

>>>

strip()

strip英文翻译:脱掉,剥夺

strip()默认移除字符串两边的空白。只是返回处理后的副本,原来的值不变。

>>> x=' tom '

>>> x

' tom '

>>> x.strip()

'tom'

>>>

也可以自己指定要去除的目标:

>>> x='ssssstomsssss'

>>> x.strip('s')

'tom'

>>> x='#######tom####'

>>> x.strip('#')

'tom'

同类的还有lstrip(),rstrip()

>>> x='#######tom####'

>>> x.lstrip('#')

'tom####'

>>> x.rstrip('#')

'#######tom'

>>>

capitalize()

capitalize()返回首字母大写的副本,不改变原来的值:

>>> x='hello,world'

>>> x.capitalize()

'Hello,world'

title()

title()返回标题样式的副本(单词首字母大写),不改变原来的值:

>>> x='hello,world'

>>> x.title()

'Hello,World'

upper()

upper()返回所有字母大写的副本,不改变原来的值:

>>> x='hello,world'

>>> x.upper

'HELLO,WORLD'

lower()

lower()返回所有字母小写的副本,不改变原来的值:

>>> x='Hello,World'

>>> x.lower()

'hello,world'

>>>

center()

center()返回一个原字符串居中,并使用空格填充至长度 width 的新字符串。默认填充字符为空格。居中显示

语法:

str.center(width[,fillchar])

width------字符串的总宽度

fillchar-----填充字符

>>> x='hello'

>>> x.center(15,'#')

'#####hello#####'

>>>

count()

count()方法用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。空格也是字符。

语法:

str.count(sub,start,end)

sub-----搜索的子字符串

start----字符串开始搜索的位置,默认为第一个字符,第一个字符索引值为0

end-----字符串中结束搜索的位置。默认为字符串的最后一个位置。

>>> x='hel lo love'

>>> x.count(' ')

2

>>> x.count('l',0,4)

1

endswith()

endswith() 方法用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False。可选参数"start"与"end"为检索字符串的开始与结束位置。

语法:

str.endswith(suffix,start,end)

suffix----该参数可以是一个字符串或者是一个元素

start----字符串开始的位置

end------字符中结束的位置

>>> x='/bin/nologin'

>>> x.endswith('n')

True

>>> x.endswith('nologin')

True

>>>

startswith()

startswith() 方法用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 beg 和 end 指定值,则在指定范围内检查。

语法:

str.startwith(str,strbegin,strend)

str-----检测的字符串。

strbegin----可选参数用于设置字符串检测的起始位置。

strend----可选参数用于设置字符串检测的结束位置

>>> x.startswith('/')

True

>>> x.startswith('/bin')

True

>>>

find()

find() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1。(没找到就返回-1)

语法:

str.find(str,begin,end)

str-----指定检索的字符串

begin----开始索引,默认为0

end-----结束索引,默认为字符串的长度

>>> x='/etc/sshd/ssh.conf'

>>> x.find('/')

0

>>> x.find('/',1,4)

-1

>>> x.find('.conf')

13

>>>

>>>> x.find('.cont')

-1

>>>

format()

format()和%格式化功能一样,基本语法是通过 {} 和:来代替以前的%。format函数可以接受不限个参数,位置可以不按顺序。

示例:

>>> msg='Nname:{},age:{},sex:{}'

>>> print(msg.format('tom',18,'male'))

Nname:tom,age:18,sex:male

>>> msg='Nname:{x},age:{y},sex:{z}'

>>> print (msg.format(x='tom',y=18,z='male'))

Nname:tom,age:18,sex:male

>>> url='https://movie.douban.com/top250?start={page}&filter=&type='

>>> print(url.format(page=50))

https://movie.douban.com/top250?start=50&filter=&type=

>>>

字符串切片

str[索引初始:索引结束:索引步长]

>>> print (x[0])

h

>>> print (x[0:3])

hel

>>> print (x[0:5:2])

hlo

>>> print (x[::-1])

dlrow olleh

>>>

>>> print (x[:-1])

hello worl

>>> print (x[1:])

ello world

>>>

简而言之,分片操作的实现需要提供两个索引作为边界,第一个索引元素包含在分片内,第二个则不包含在分片内。

对于分片还可以使用更大的步长,步长为负数的时候,从尾部开始取数据

isdigit()

digit英文解释:数字

isdigit()判断字符串内是否全是数字。如果字符串只包含数字则返回 True 否则返回 False。

>>> x='12345'

>>> x.isdigit()

True

>>> x='3.1415'

>>> x.isdigit()

False

>>>

isalpha()

isalpha() 方法检测字符串是否只由字母组成。如果字符串至少有一个字符并且所有字符都是字母则返回 True,否则返回 False

>>> x='adswqeq '

>>> x.isalpha()

False

>>> x='a'

>>> x.isalpha()

True

>>>

index()

index() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,该方法与 python find()方法一样,只不过如果str不在 string中会报一个异常。

>>> x='/etc/sshd/ssh.conf'

>>> x.index('/')

0

>>> x.index('/',1,4)

Traceback (most recent call last):

File "", line 1, in

x.index('/',1,4)

ValueError: substring not found

>>> x.index('.conf')

13

>>> x.index('.cont')

Traceback (most recent call last):

File "", line 1, in

x.index('.cont')

ValueError: substring not found

>>>

replace()

replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。

语法:

str.replace(old,new,max)

old----将被替换的子字符串

new----新字符串,用于替换old子字符串

max----指定替换次数

>>> x='this is test'

>>> x.replace('is','are')

'thare are test'

>>> x.replace('is','are',1)

'thare is test'

>>> x.replace('is','are',2)

'thare are test'

>>> x.replace('is','are',3)

'thare are test'

>>>

split()

split()通过指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串

语法:

str.split('分隔符',分隔次数)

分隔符默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。

>>> x='root:x:0:0::/root:/bin/bash'

>>> x.split()

['root:x:0:0::/root:/bin/bash']

>>> x.split(':')

['root', 'x', '0', '0', '', '/root', '/bin/bash']

>>> x.split(':',2)

['root', 'x', '0:0::/root:/bin/bash']

>>> x.split(':',3)

['root', 'x', '0', '0::/root:/bin/bash']

>>>

isspace()

isspace() 方法检测字符串是否只由空格组成。

语法:

str.isspace()

如果字符串中只包含空格,则返回 True,否则返回 False.和将一段空字符串使用strip处理后判断是否等于''一样。

>>> x = ' '

>>> x.isspace()

True

>>> x.strip() == ''

True

>>>

swapcase()

swapcase() 方法用于对字符串的大小写字母进行转换。

语法

str.swapcase()

返回大小写字母转换后生成的新字符串。

>>> x = '''it's good!'''

>>> x.swapcase()

"IT'S GOOD!"

>>> x = 'Ab'

>>> x.swapcase()

'aB'

>>>

ljust()和rjust()

ljust() 方法返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。

语法:

str.ljust(width,fillchar)

width-----指定字符串长度

fillchar----填充字符,默认为空格

>>> x = 'tom'

>>> x.ljust(10,'#')

'tom#######'

rjust() 方法返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串。如果指定的长度小于字符串的长度则返回原字符串。

示例:

>>> x = 'tom'

>>> x.rjust(10,'#')

'#######tom'

>>>

序号方法及描述

1capitalize()

将字符串的第一个字符转换为大写

2

3

4

5

6endswith(suffix, beg=0, end=len(string))

检查字符串是否以 obj 结束,如果beg 或者 end 指定则检查指定的范围内是否以 obj 结束,如果是,返回 True,否则返回 False.

7

8

9

10

11

12

13

14

15

16

17

18

20

21

22

23

24

25

26

29

30

31

32

33

34

35

36

37

38

39

40

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值