学习笔记之Python数据类型-String

本文介绍了Python中字符串的基本概念、常用操作方法及实例演示,包括字符串的定义、比较、拼接、查找、分割、翻转、计数等。适用于初学者快速掌握Python字符串处理技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

字符串

字符串或串(String)是由数字、字母、下划线组成的一串字符。一般记为s=“a1a2···an”(n>=0)。它是编程语言中表示文本的数据类型。

两个字符串相等的充要条件是:长度相等,并且各个对应位置上的字符都相等。

Python中,用引号括起来的都是字符串,其中的引号可以是单引号也可以是双引号,甚至可以是三引号:

' abc ' 单引号

"abc" 双引号

''' abc ''' 三个单引号

""" abc"""  三个双引号  

字符串替换

使用replace()方法
>>> s1 = 'hello world'
>>> s1.replace('hello','hi')
'hi world'

字符串比较

cmp()方法
比较的是字符串中每个字符的ASCII码的大小,从左到右依次比较,相等返回0, 前者大于后者返回1,前者小于后者返回-1.
例如:
>>> s1
'hello world'
>>> s2
'hello python'
>>> s3
'hello world'
>>> cmp(s1,s2)
1
>>> cmp(s2,s1)
-1
>>> cmp(s1,s3)
0

字符串拼接

通过加号“+”完成,例如:
>>> s1 ='hello'
>>> s2 ='world'
>>> s1 + s2
'helloworld'
>>> s1 + ' ' + s2
'hello world'
#通过字符串*数字的方式可以将字符串多次打印
>>> s1 * 3
'hellohellohello'

字符串查找

字符串查找可以通过index()方法和find()方法来实现,返回第一次查找到的字符在字符串中的索引值。其中,当所查找的字符在字符串中不存在时,使用index()方法查找会报错,而使用find()方法会返回-1. 例如:
>>> s = 'hello'
>>> s.find('h')    #注意()中的字符一定用引号引起来,不然python会认为这是一个未声明的变量,从而报错
0
>>> s.index('h')
0
>>> s.find('r')
-1
>>> s.index('r')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found
#使用rfind()实现倒序查找
>>> s.find('l')
2
>>> s.rfind('l')
3

字符串分割

split()方法可以实现字符串的分割。
>>> s = 'ZhangSan@LiSi@WangWu'
>>> s
'ZhangSan@LiSi@WangWu'
>>> s.split('@')
['ZhangSan', 'LiSi', 'WangWu']

字符串翻转

即字符串的倒序输出:
>>> s = 'hello'
>>> s[::-1]
'olleh'

字符串计数

count()方法,计算字符串中某字符出现的次数。
>>> s
'hello'
>>> s.count('h')
1
>>> s.count('r')
0
>>> s.count('l')
2

将字符串中的tab扩展成空格

expandtabs()方法,默认是扩展成8个空格。
注意扩展不是替换,例如:
>>> s = "this is\tstring"
>>> s
'this is\tstring'
>>> s.expandtabs()    #默认扩展成8个,this is占用7个字符,所以空格数为1.  7+1=8
'this is string'
>>> s.expandtabs(3)   #扩展成3个字符,this is为7个字符,相当于3+3+1,剩余一个字符,所以空格数为2.   1+2=3
'this is  string'
>>> s.expandtabs(5)  
'this is   string'
>>> s.expandtabs(16)
'this is         string'

字符串的判断

isalnum() 判断字符串是否含有数字和字母,全部包含返回true, 否则返回false.
>>> a = 'this is string'
>>> b = 'this is string123'
>>> a.isalnum()
False
>>> b.isalnum()
False
isalpha()判断字符串是否仅含有字母,是返回true, 否返回false.
>>> a  = 'abc'
>>> b = 'a b c'
>>> a.isalpha()
True
>>> b.isalpha()
False
isdigit()判断字符串是否仅含有数字
>>> a = 'hi123'
>>> b = '123'
>>> a.isdigit()
False
>>> b.isdigit()
True
lstrip()删除字符串中所有的前导空格
>>> a
'       hello      '
>>> a.lstrip()
'hello      '
rstrip()删除字符串中所有的行尾空白
>>> a
'       hello      '
>>> a.rstrip()
'       hello'







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值