【Python】常用字符串api

1 strip()方法

去除字符串中指定的字符

s = "123abc   "
s.strip(" ")   # 去除空格
s = "123abc"

2 replace()方法

替换指定字符为其他字符

s = "123abc   "
s.replace(" ","1")	# 将空格替换为1
s = "123abc111"

去除 回车\r换行符\n

s.replace('\n', '').replace('\r', '')

3 大小写转换

str = "www.runoob.com"
print(str.upper())          # 把所有字符中的小写字母转换成大写字母
print(str.lower())          # 把所有字符中的大写字母转换成小写字母
print(str.capitalize())     # 把第一个字母转化为大写字母,其余小写
print(str.title())          # 把每个单词的第一个字母转化为大写,其余小写 

WWW.RUNOOB.COM
www.runoob.com
Www.runoob.com
Www.Runoob.Com

4 isalnum()方法

检测字符串是否由 字母数字 组成

str = "this2009";  # 字符中没有空格
print(str.isalnum());
str = "this is string example....wow!!!";  # 字符中有空格
print(str.isalnum());

True
False

5 find()方法

从下标0开始,查找在字符串里第一个出现的子串的位置(索引号)

info = 'abca'
print(info.find('a'))	# 返回结果:0
>> 0

6 字符串去重

使用 set() 方法

s = "123ab11111"
b = set(s)
>> {'a', 'b', '2', '3', '1'}
a = "".join(list(b))
>> 'ab231'

7 拼接与拆分

拼接 join() 方法
拆分 split() 方法

str = "this is string example....wow!!!"
print (str.split( ))       # 以空格为分隔符
print (str.split('i',1))   # 以 i 为分隔符
print (str.split('w'))     # 以 w 为分隔符

['this', 'is', 'string', 'example....wow!!!']
['th', 's is string example....wow!!!']
['this is string example....', 'o', '!!!']
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值