python学习笔记:(六)str(字符串)常用方法

注意点:

  1、字符串是不可变的;

  2%格式化操作符:左侧放置字符串,右侧放置希望被格式化的值。

  对于单个字符的编码,Python提供了ord()函数获取字符的整数表示,chr()函数把编码转换为对应的字符

  以Unicode表示的str通过encode()方法可以编码为指定的bytes

常用方法

1substitute()

  替换指定变量的值(替换全部)

 

1 #substitute
2 from string import Template
3 s=Template('$x,glorious $x!')
4 print(s.substitute(x='stone'))

 

  替换部分

 

1 m=Template("This is s${a}one")
2 print(m.substitute(a='t'))

 

2find()

  在一个比较长的字符串中查找子串,返回子串所在位置的最左端索引

1 str01="chinachinachinachinachina"
2 print(str01.find('na'))

 

3join()

  用来连接序列的元素

1 #join
2 dir1='0','1','2','3'
3 
4 print('/'.join(dir1))

 

4lower()

  返回小写字母

 

1 #lower
2 str001='WERWERSDFsdfWERWER123'
3 print(str001.lower())

 

5title()

  以标题的方式显示

1 #title
2 str001=" tHis is mytitle"
3 print(str001.title())

 

6capitalize()

1 #capitalize
2 str001=" tHis is Mytitle"
3 print(str001.capitalize())

 

7replace()

  替换

#replace:替换
str001="this  is mytitle"
print(str001.replace('is','aha'))

 

8split()

  将字符串分割成序列

 

1 #split
2 str001="this is mytitle"
3 print(str001.split())

 

9strip()

  返回去除两侧(不包含内部)空格的字符串

1 #strip
2 str001=" this is mytitle    "
3 str002="**this is mytitle**"
4 print(str001)
5 print(str001.strip())
6 print(str002)
7 print(str002.strip("*"))

 

10translate()

  替换,只处理单个字符

 

1 #translate
2 str001="a"
3 print(str001.translate('h')) 

转载于:https://www.cnblogs.com/smallstone2018/p/10045490.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值