python-4 字符串相关str

1:访str单个字符

#for循环迭代
name = 'Chengwei'
for ch in name:
    print(ch, end=' ')
#C h e n g w e i

#索引

print(name[1])
#h
print(name[-1]) #最后一个为 -1
#i

#len()函数返回str字符串数量

print(len(name))
#8

2: 字符串连接

message = 'hello' + 'world'
print(message)
#helloworld

3:str是不可变的

4:str切片

message = 'helloworld'
print(message[2:4])
#ll

5:使用in 和not in 测试字符串

message = 'helloworld'
if 'hello' in message:
    print('YES')
#YES
if 'aaa' not in message:
    print('YES')
#YES

6:str方法

字符串测试方法

isalnum()如果str只包含字母或数字,并且长度至少为一个字符,则返回true。否则返回false
isalpha()如果str只包含字母并且长度至少为一个字符,则返回true。否则返回false
isdigit()如果str只包含数字如果str只包含字母并且长度至少为一个字符,则返回true。否则返回false
islower()

如果str中的所有字母都是小写如果str只包含数字如果str只包含字母并且长度至少为一个字符,则返回true。否则返回false

isspace()如果str只包含空白字符,并且长度至少为一个字符,则返回true。否则返回false(空格,\n,\t)
isupper()

如果str中的所有字母都是大写如果str只包含数字如果str只包含字母并且长度至少为一个字符,则返回true。否则返回false

字符串修改方法

lower()返回将所有字母转换为小写的str副本。不是字母的不变
lstrip()返回删除所有前导空白字符的str副本。
lstrip(str_item)str_item是字符串。返回删除所有前导str_item的字符串副本
rstrip()返回所有尾部空白字符串的字符串副本。
rstrip(str_item)返回删除所有尾部str_item的字符串副本
strip()
strip(str_item)删除所有前导和尾部str_item的字符串副本
upper()

搜索和替换的方法

endswith(substring)返回true或false
find(substring)返回找到substring的最小索引位置。没有找到返回 -1
replace(old, new)返回将所有的old替换为new的字符串副本
starstwith(substring)返回true或false

7:重复操作符

print('hello' * 2)
#hellohello

8:分割字符串

message = 'hello world chengwei'
message_list = message.split()
print(message_list)
#['hello', 'world', 'chengwei']

message = 'hello,world,chengwei'
message_list = message.split(',')
print(message_list)
#['hello', 'world', 'chengwei']

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值