注意点:

  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')) 

相关文章:

  • 2021-12-21
  • 2021-07-16
  • 2021-12-29
  • 2021-07-28
  • 2022-01-11
  • 2022-12-23
猜你喜欢
  • 2021-06-11
  • 2021-11-16
  • 2021-12-10
  • 2021-12-23
  • 2022-12-23
  • 2021-06-28
相关资源
相似解决方案