python中strip、startswith、endswith

本文介绍如何使用Python内置方法strip、startswith及endswith进行字符串处理,包括去除空白字符及查找特定开头与结尾的字符串。

strip(rm)用来删除元素内的空白符:

rm对应要删除空白符的元素,当rm为空(strip())时删除所有元素的空白符

startswith、endswith用来查找开头或结尾条件的元素

例子:

 1 li = ["alec", " aric", "Alex", "Tony", "rain"]
 2 tu = ("alec", " aric", "Alex", "Tony", "rain") 
 3 dic = {'k1': "alex", 'k2': ' aric',  "k3": "Alex", "k4": "Tony"}
 4 for i in li:
 5     b = i.strip()
 6     if (b.startswith("a") or b.startswith("A")) and b.endswith("c"):
 7         print(b)
 8 
 9 for i in tu:
10     b = i.strip()
11     if (b.startswith("a") or b.startswith("A")) and b.endswith("c"):
12         print(b)
13         
14 for i in dic:
15     b = dic[i].strip()
16     if (b.startswith("a") or b.startswith("A")) and b.endswith("c"):
17         print(b)

上面代码:查找以 a或A开头并且以 c 结尾的所有元素,并输出

输出结果:

alec
aric
alec
aric
aric

 

转载于:https://www.cnblogs.com/zhangzengqiang/p/7499339.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值