字符串相关命令

1.常用命令

1)isdecimal 判断是不是十进制(整数)

2)endswith 判断字符串结尾是否为指定字符

3)startswith 判断字符串开头是否为指定字符

4)count 判断字符串中某个特定字符的数量

5)title 将字符串变为抬头形式(单词首字母大写)

6)index 从左往右寻找某特定字符串的位置,并输出该位置,若没有则报错(字符串定位从0开始)

7)rindex 从右往左寻找某特定字符串的位置,并输出该位置,若没有则报错(字符串定位从0开始)

8)upper 把字符串变为大写

9)lower 把字符串变为小写

10)isupper 判断字符串是否全部为大写

11)islower 判断字符串是否全部为小写

12)isalpha 判断字符串是否全部是字母

13)isalnum 判断字符串是否为数字、字母或者数字和字母的组合

14)isdigit 判断字符串是否为整数

15)isspace 判断字符串是否全部为空格

16)find 从左往右寻找某特定字符串的位置,并输出该位置,若没有则返回-1(字符串定位从0开始)

2.须牢记命令

1)split 从左往右以指定的分隔符将字符串分割为列表,可指定分割次数

  print(msg.split('.',1))

2)join 把可迭代对象变为字符串(可迭代对象:列表、元组、字典、字符串、集合)

3)replace 将特定字符替换,并可以指定替换次数

  print(msg.replace('.','|',1))

4)strip 去除字符串两边的指定字符,默认为空格

  lstrip 去除左边 rstrip 去除右边

5)encode 转码 把字符串变为bytes类型

  utf-8 一个汉字占三个字节,生僻字占更多

6)decode 解码

7)format 格式化输出

  name = 'litong'

  age = 22

  res = 'my name is {},my age is {}'.format(name,age)

  res = 'my name is {1},my age is {0}'.format(name,age)

  res = 'my name is {n},my age is {a}'.format(n=name,a=age)

  print(res)

  my name is litong,my age is 22

  my name is 22,my age is litong

  my name is litong,my age is 22

8)%s %d %f 占位符格式化输出

  high = 192.2

  used = 89

  res = 'my high is %.2f%%' % used

  print(res)

  my high is 89.00%

9)字符串拼接

  a = '1'

  b = '2'

  print(a+b)

  12

10)字符串相乘

  print('=' * 5)

   

  =====

原文地址:https://www.cnblogs.com/Agnostida-Trilobita/p/11007821.html