python中字符串的操作方法总结(代码示例)


本文摘自php中文网,作者不言,侵删。

本篇文章给大家带来的内容是关于python中字符串的操作方法总结(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

String(字符串):

定义和创建字符串:

定义:字符串是一个有序的字符的集合,用于存储和表示基本的文本信息。
注意:字符串的单引号和双引号都无法取消特殊字符的含义,如果想让引号内

1

2

var1='Hello World!'

print (var1)

对应操作:

1,“*”重复输出字符串

1

print('Hello World'*2)

2,"[]","[:]" 通过索引获取字符串中字符,这里和列表的切片操作是相同的

1

print('Hello World'[2: ])

3, "in" 成员运算符 如果字符串中包含给定字符返回 True

1

print('el' in 'Hello World')

4,"%"格式字符串

1

2

print('alex is a good teacher')

print('%s is a good teacher' %'alex')

5,"+" 字符串拼接

1

2

3

4

a ='123'

b='abc'

c=a+b

print(c)

注:“+”效率低,改用 join

1

2

c=''.join([a,b])

print(c)

字符串常用方法:

字符串的替换、删除、截取、复制、连接、比较、查找、分割

#capitalize:首字母大写,其他字母小写

1

2

3

s='asf sgs SD dfs ASdf'

print(s.capitalize())

>>Asf sgs sd dfs asdf

#lower() 转换为小写
#upper() 转换为大写
#swapase() 大小写互换

1

2

3

4

5

6

7

8

9

a='hello word'

print(a.upper())

b='HELLO WORD'

print(b.lower())

c='hello WORD'

print(c.swapcase())

>>HELLO WORD

>>hello word

>>HELLO word

#s.strip():删除字符串两边的指定字符,默认为空值

1

2

3

4

s='     hello    '

b=s.strip()

print(b)

>>hello

#s.lstrip():删除字符串左边的指定字符,
#s.rstrip():删除字符串左边的指定字符,

1

2

3

4

5

6

7

s='     hello    '

b=s.ltrip()

c=s.rtrip()

print(b)

print(c)

>>hello

>>    hello

#复制字符串

1

2

3

4

a='hello'

b=a*2

print(b)

>>hellohello

#连接2个字符串str.join

1

2

3

4

5

a='hello'

b='123'

a.join(b)

print(a.join(b))

>>1hello2hello3

#查找字符串str.index;str.find功能相同。
区别在于index查找不到,报错。find查找不到返回‘-1’.两个找到,都返回第一个找的的位置

1

2

3

4

5

a='hello word'

print(a.index('w'))

print(a.find('a'))

>>6

>>-1

#判断是否包含指定字符串‘in’,‘not in’

1

2

3

4

5

a='hello word'

print('hello' in a)

print('hello' not in a)

>>True

>>False

#查看字符串的长度 len

1

2

3

a='hello word'

print(len (a))

>>10

#srt.centen 将字符串放入中心位置可指定长度以及位置两边字符

1

2

3

a='chen zheng'

print(a.center(20,"*"))

>>*****chen zheng*****

1

2

3

4

#str.count()  统计字符串出现的次数

a='hello word'

print(a.count('l'))

>>2

1

2

3

4

5

6

7

8

9

10

11

#

S='prefix123aaasuffix'

print(S.startswith('prefix'))  #是否以prefix开头

print(S.endswith('suffix'))    #以suffix结尾

print(S.isalnum())             #是否全是字母和数字,并至少有一个字符

print(S.isalpha())             #是否全是字母,并至少有一个字符

print(S.isdigit())             #是否全是数字,并至少有一个字符

print(S.isspace())             #是否全是空白字符,并至少有一个字符

print(S.islower())             #S中的字母是否全是小写

print(S.isupper())             #S中的字母是否便是大写

print(S.istitle())             #S是否是首字母大写的

以上就是python中字符串的操作方法总结(代码示例)的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

Python中如何安装pip

Python爬虫任务接单渠道

Python中什么是对象

信息竞赛一定要Python

爬虫Python能做什么?

Python怎么不换行打印

Python中子类如何调用父类函数的代码示例

Python怎么退出for循环

盘点Python中的常用术语

Python怎么批量注释

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...