python基础那些事(二)

字符串
切片
序列列[开始位置下标:结束位置下标:步长]
不包含结束位置下标对应的数据, 正负整数均可;
步长是选取间隔,正负整数均可,默认步长为1。
例子

name = "abcdefg"
print(name[2:5:1]) # cde
print(name[2:5]) # cde
print(name[:5]) # abcde
print(name[1:]) # bcdefg
print(name[:]) # abcdefg
print(name[::2]) # aceg
print(name[:-1]) # abcdef, 负1表示倒数第⼀一个数据
print(name[-4:-1]) # def
print(name[::-1]) # gfedcba

查找
所谓字符串查找方法即是查找子串在字符串中位置或出现的次数。
find():检测某个子串是否包含在这个字符串中,如果在返回这个子串开始的位置下标,否则则返回-1.
语法
字符串串序列列.find(⼦子串串, 开始位置下标, 结束位置下标)

注意:开始和结束位置下标可以省略,表示在整个字符串序列列中查找。

mystr = "hello world and itcast and c++and Python"
print(mystr.find('and')) # 12
print(mystr.find('and', 15, 30)) # 23
print(mystr.find('ands')) # -1

index():检测某个⼦串是否包含在这个字符串串中,如果在返回这个⼦串开始的位置下标,否则报异常。
字符串串序列列.index(⼦子串串, 开始位置下标, 结束位置下标)

rfind(): 和find()功能相同,但查找⽅方向为右侧开始。
rindex():和index()功能相同,但查找⽅方向为右侧开始。
count():返回某个⼦子串串在字符串串中出现的次数

字符串串序列列.count(⼦子串串, 开始位置下标, 结束位置下标)

replace():替换
字符串串序列列.replace(旧⼦子串串, 新⼦子串串, 替换次数)

mystr = "hello world and itcast and c++ and Python"
# 结果:hello world he itcast he c++ he Python
print(mystr.replace('and', 'he'))
# 结果:hello world he itcast he c++ he Python
print(mystr.replace('and', 'he', 10))
# 结果:hello world and itcast and c++ and Python
print(mystr)

split()
字符串串序列列.split(分割字符, num)
注意:num表示的是分割字符出现的次数,即将来返回数据个数为num+1个。

mystr = "hello world and itcast and itheima and Python"
	# 结果:['hello world ', ' itcast ', ' c++', ' Python']
print(mystr.split('and'))
	# 结果:['hello world ', ' itcast ', ' c++and Python']
print(mystr.split('and', 2))
	# 结果:['hello', 'world', 'and', 'itcast', 'and', 'c++', 'and', 'Python']
print(mystr.split(' '))
	# 结果:['hello', 'world', 'and itcast and c++ and Python']
print(mystr.split(' ', 2))

join():⽤用⼀一个字符或⼦串合并字符串,即是将多个字符串合并为⼀一个新的字符串。

字符或子串.join(多字符串组成的序列)
list1 = ['chuan', 'zhi', 'bo', 'ke']
t1 = ('aa', 'b', 'cc', 'ddd')
# 结果:chuan_zhi_bo_ke
print('_'.join(list1))
# 结果:aa...b...cc...ddd
print('...'.join(t1))

capitalize():将字符串第一个字符转换成大写
title():将字符串每个单词首字母转换成⼤写。
lower():将字符串中大写转小写。
upper():将字符串中小写转大写。
strip():删除字符串两侧空⽩字符

判断
startswith():检查字符串是否是以指定⼦串开头,是则返回 True,否则返回 False。如果设置开
始和结束位置下标,则在指定范围内检查

字符串序列.startswith(⼦串, 开始位置下标, 结束位置下标) 
字符串序列.endswith(⼦串, 开始位置下标, 结束位置下标) 

isalpha():如果字符串至少有⼀一个字符并且所有字符都是字⺟母则返回 True, 否则返回 False。
isdigit():如果字符串串只包含数字则返回 True 否则返回 False。
isalnum():如果字符串⾄至少有⼀一个字符并且所有字符都是字母或数字则返 回 True,否则返回
False。
**isspace():**如果字符串串中只包含空⽩白,则返回 True,否则返回 False。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值