字符串操作

字符串
  • 字符串也是一种序列,因此通用的序列操作,如索引、分片、乘法等对它同样适配
  • 字符串与元组一样,不可变,即不能进行赋值操作
  • 索引从0开始
str = "hello world!"
print(str[2])	# 根据索引获取第3个元素
print(str[:2])
print(str[1:3])
print(str + "字符串加法运算!")
print(str*2)

l
he
el
hello world!字符串加法运算!
hello world!hello world!

find
  • find 方法用于在一个字符串中查找子串,它返回子串所在位置的最左端索引,如果没有找到,则返回 -1。
motto = "to be or not to be, that is a question"
print(motto.find('be'))         # 获取第一个b在字符串中的索引,索引从0开始
print(motto.find('be', 4))      # 从索引4开始找b
print(motto.find('be', 4, 7))   # 在索引4~7之间找字符b,没有找到则返回-1

3
16
-1

split
  • split 方法用于将字符串分割成序列
  • 如未指定分隔符,则默认根据空格分割
users = [("001,002,005,008")]   # 此为一个任务的执行人,执行人有多个,需要根据逗号分割,获取执行人ID
user_list = users[0].split(',')     # 根据逗号分割
print(user_list, type(user_list))   # 分割成列表

[‘001’, ‘002’, ‘005’, ‘008’] <class ‘list’>

join
new_users = ','.join(user_list)     # join将列表中元素根据制定字符连接
print(new_users, type(new_users))   # 拼接后变为字符串

001,002,005,008 <class ‘str’>

strip
hello1 = '   Hello World   '
hello2 = '#2#Hello World#1#'
new_hello1 = hello1.strip()     # 移除字符串两边的空格
print(new_hello1)
new_hello2 = hello2.strip('#12 ')       # 移除字符串两边的# or 1 or 2 or 空格
print(new_hello2)

Hello World
Hello World

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值