Python 字符串基本操作

一、字符串拼接 + -

  • 字符串和字符串可以拼接,但是不能直接和其他数据进行拼接,需要用 str() 来转换
str1 = '中华人民共和国成立'
num = 72
str2 = '周年'
print(str1 + str(num) + str2)

输出结果:

中华人民共和国成立72周年

二、获取字符串的长度 - len()

  • 通过 len() 计算字符串长度时,不区分英文、数字和汉字,都按一个字符计算
  • utf-8 编码的字符串,一个汉字当3个字节
  • gbk 编码的字符串,一个汉字当2个字节
  • 字符串的编码与解码(encode、decode)
In [4]:msg = '资本家需要一个路灯'

In [5]:len(msg)
Out[5]: 9

In [6]:msg_utf = msg.encode('utf-8')  # 字符串编码

In [7]:msg_gbk_decode = msg_gbk.decode('gbk')  # 字符串解码

In [8]:msg_gbk_decode
Out[8]: '资本家需要一个路灯'

In [9]:msg_utf
Out[9]: b'\xe8\xb5\x84\xe6\x9c\xac\xe5\xae\xb6\xe9\x9c\x80\xe8\xa6\x81\xe4\xb8\x80\xe4\xb8\xaa\xe8\xb7\xaf\xe7\x81\xaf'

In [10]:len(msg_utf)
Out[10]: 27

In [11]:msg_gbk = msg.encode('gbk')  # 字符串编码

In [12]:msg_gbk
Out[12]: b'\xd7\xca\xb1\xbe\xbc\xd2\xd0\xe8\xd2\xaa\xd2\xbb\xb8\xf6\xc2\xb7\xb5\xc6'

In [13]:len(msg_gbk)
Out[13]: 18

三、字符串截取(切片运算)

  • 字符串切片运算:str[start : end : step]
  • 截取子串是含头不含尾
In [43]:msg = '实践出真知'

In [44]:msg[1]
Out[44]: '践'

In [46]:msg[:4]
Out[46]: '实践出真'

In [45]:msg[1:4]
Out[45]: '践出真'

In [48]:msg[-4]
Out[48]: '践'

In [51]:msg[-4:-1]
Out[51]: '践出真'

In [52]:msg[-1:-4:-1]
Out[52]: '知真出'

In [53]:msg[::]
Out[53]: '实践出真知'

In [54]:msg[::-1]
Out[54]: '知真出践实'

四、字符串分隔 - split()

  • split() 方法语法:str.split(" ", num)
  • " " 为间隔,分割 num
In [1]:text = 'I like you but I dont love you'

In [2]:word = text.split(' ')  # 以' '为间隔

In [3]:word
Out[3]: ['I', 'like', 'you', 'but', 'I', 'dont', 'love', 'you']

In [4]:word = text.split(' ', 2)  # 分割2次

In [5]:word
Out[5]: ['I', 'like', 'you but I dont love you']

五、字符串合并 - join()

  • join()方法语法:str.join(sequence)
  • sequence – 要连接的可迭代序列
In [10]:ip = ['192', '168', '1', '1']

In [11]:ip_address = '.'.join(ip)

In [12]:ip_address
Out[12]: '192.168.1.1'

六、检索子串出现次数 - count()

  • count() 用于统计字符串里某个字符或子字符串出现的次数。
  • count()方法语法:str.count(sub, start, end)
  • sub – 搜索的子串
  • start – 字符串开始搜索的位置。默认为第一个字符。
  • end – 字符串中结束搜索的位置。默认为字符串的最后一个位置。
In [16]:text = 'I like python I love java I learn python'

In [17]:text.count('I')
Out[17]: 3

In [18]:text.count('I', 3)
Out[18]: 2

In [22]:text.count('I', 12, 18)  # 包含空格
Out[22]: 1

In [24]:text.count('b')
Out[24]: 0

七、检索子串出现位置

1、find()

  • find() 用于检测字符串中是否包含子串 ,如果指定 startend 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回 -1。
  • find() 语法:str.find(sub, start, end)
  • sub – 指定搜索的子串
  • start– 开始索引,默认为0
  • end – 结束索引,默认为字符串的长度
In [26]:ip_address = '192.168.1.1'

In [27]:ip_address.find('.')
Out[27]: 3

In [28]:ip_address.find('.', 3 + 1)
Out[28]: 7

In [29]:ip_address.find('.', 7 + 1)
Out[29]: 9

In [30]:ip_address.find('.', 9 + 1)
Out[30]: -1

2、index()

  • 区别于 find() :如果子串没找到,他会 抛出一个值错误
In [1]:ip_address = '192.168.1.1'

In [2]:ip_address.index('.', 7 + 1)
Out[2]: 9

In [3]:ip_address.index('.', 9 + 1)
Traceback (most recent call last):

  File "<ipython-input-32-75caeb563e17>", line 1, in <module>
    ip_address.index('.', 9 + 1)

ValueError: substring not found

八、检查是否以指定子串开头 - startswith()

  • startswith() 用于检查字符串是否以指定子串开头,如果是则返回 True,否则返回 False。
  • startswith() 语法:str.startswith(sub, start, end)
  • sub – 检测的子串。
  • start– 可选参数,起始位置。
  • end – 可选参数,结束位置。
names = ['张美玉', '王美与', '张玉梅', '刘美玉']
text = 'This is a book'

print(text.startswith('This'))
print(text.startswith('This', 1))

for name in names:
    if name.startswith('张'):
        print(name)

输出结果:

True
False
张美玉
张玉梅

九、检查是否以指定子串结尾 - endswith()

  • 参数和返回值和 startswith() 一样
In [10]:file_name = 'lost river.mp3'

In [11]:file_name.endswith('mp3')
Out[11]: True

检索全部 mp3 类型的文件

files = ['同志.txt', 'QQ.exe', '夜曲.Mp3', '霍元甲.docx', '青花瓷.mp3']

for file in files:
    if file.lower().endswith('mp3'):
        print(file.lower())

输出结果:

夜曲.mp3
青花瓷.mp3

十、字符串替换 - replace()

  • replace() 语法:str.replace(old, new[, count])
  • old – 将被替换的子字符串。
  • new – 新字符串,用于替换 old 子字符串。
  • count – 可选字符串, 替换不超过 count 次。count = -1 表示替换所有
text = 'I喜欢python,I喜欢java,I学python'
text1 = text.replace('I', '我', 1)
text2 = text.replace('I', '我')
text3 = text.replace('I', '我', -1)
text4 = text.replace('I', '我', 8)
print(text1, text2, text3, text4, sep='\n')

输出结果:

我喜欢python,I喜欢java,I学python
我喜欢python,我喜欢java,我学python
我喜欢python,我喜欢java,我学python
我喜欢python,我喜欢java,我学python

十一、字符串大小写转换

  • 转换成大写 - str.upper()
  • 转换成小写 - str.lower()
  • 转换成标题函数 - str.title()
In [18]:msg = 'welCome to pyTHon world'

In [19]:msg.upper()
Out[19]: 'WELCOME TO PYTHON WORLD'

In [20]:msg.lower()
Out[20]: 'welcome to python world'

In [21]:msg.title()
Out[21]: 'Welcome To Python World'
  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

iFulling

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值