检测机制


  1. startswith

    1. "Brevity is the soul of wit".startswith("Bre")
    2. >>True
    3. #判断索引[1,3)中的元素,值是否为"re"
    4. "Brevity is the soul of wit".startswith("re",1,3)
    5. >>True
  2. endswith

    1. "Brevity is the soul of wit".endswith("re",1,3)
    2. >>True
  3. isupper 判断是否至少存在一个大写字母,且所有字母均大写

    1. "BREVITY你好 \n123".isupper()
    2. >>True
  4. islower 判断是否至少存在一个小写字母,且所有字母均小写

    1. "brevity你好 \n123".islower()
    2. >>True
  5. isdigit 判断是否全部为非负整数

    1. "-1\n\r".isdigit()
    2. >>False
    3. "1".isdigit()
    4. >>True
  6. isalpha 判断是否全部为字母

    1. "Aaasdwe".isalpha()
    2. >>True
    3. "a\rs".isalpha()
    4. >>False
  7. isalnum 判断是否全部为非负整数或字母(即 isdigit or isalpha)

    1. "A 1".isalnum()
    2. >>False
    3. "A231SD".isalnum()
    4. >>True
  8. isspace 判断是否全为空格(包含制表符)

    1. "\r\n\t ".isspace()
    2. >>True
    3. "".isspace()
    4. >>False
  9. istitle 判断是否为首字母大写(忽略非字母字符)

    1. "Brevity is the soul of wit".istitle()
    2. >>False
    3. "Brevity Is The Soul Of Wit".istitle()
    4. >>True
  10. isdecimal 判断是否全为阿拉伯数字非负整数(只接受unicode形式输入)

    1. "1".isdecimal()
    2. >>AttributeError:"str" object has no attribute "isdecimal"
    3. u"3".isdecimal()
    4. >>True
    5. u"IV".isdecimal()
    6. >>False
  11. isnumeric 判断是否全为非负整数(只接受unicode形式输入)

    1. u"1".isnumeric()
    2. >>True
    3. u"一".isnumeric()
    4. >>True
    5. u"壹仟".isnumeric()
    6. >>True
  12. isidentifier 判断是否为python内部关键字或有效标志符

    1. "def".isidentifier()
    2. >>True
    3. " is".isidentifier()
    4. >>False
    5. " ".isidentifier()
    6. >>False
  13. isprintable 判断是否可打印(包括空字符串)

    1. "\b".isprintable()
    2. >>False
    3. "\t".isprintable()
    4. >>False
    5. "\n".isprintable()
    6. >>False
  14. isascii 判断是否为ascii码

    1. "二".isascii()
    2. >>False
    3. "`".isascii()
    4. >>True
    5. "】".isascii()
    6. >>False

    查找元素位置


  1. find(start: SupportsIndex |None= …, end: SupportsIndex |None= …),查找某个元素在字符串中第一次出现的索引位置,不存在返回-1

start表示起始索引位置,end表示终止位置,左闭右开

  1. c = 'adsadaasdd'
  2. c.find('d',0)
  3. >>1
  4. c.find('d',3)
  5. >>4
  6. c.find('d',1)
  7. >>1 #显示为1
  1. rfind(start: SupportsIndex |None= …, end: SupportsIndex |None= …),查找某个元素在字符串中最后一次出现的索引位置,不存在返回-1

start表示起始索引位置,end表示终止位置,左闭右开

  1. c = 'adsadaasdd'
  2. c.rfind('d',0)
  3. >>9
  4. c.rfind('d',3)
  5. >>9
  6. c.rfind('d',3,6)
  7. >>4
  8. c.rfind('d',3,9)
  9. >>8 #不显示9,
  1. index()和find()基本一致,只不过不存在会报异常
  2. rindex()和rfind()基本一致,只不过不存在会报异常

    统计字符串中某个元素的数量


count(a),用来统计字符串中某个元素的数量,不存在的则为返回0

  1. str = 'adsada231ada'
  2. num_a = str.count('a')
  3. print(num_a)
  4. >>5

首字母大写


  1. 使用内置的capitalize()函数
  2. 切片字符串然后使用upper()将单一字符变为大写再拼接
    1. s1 = 'hello'
    2. s1.capitalize()
    3. print(s1)
    4. s1 = s1[0].upper()+s1[1:]
    5. print(s1)
    6. >>Hello
    7. s2 = 'hello world'
    8. s2_arr = s2.split(" ")
    9. new_str = f'{s2_arr[0].capitalize()} {s2_arr[1].capitalize()}'
    10. print(new_str)
    11. >>Hello World

格式化整数


format()功能更强大,该函数把字符串当成一个模板,通过传入的参数进行格式化,并且使用大括号‘{}’作为特殊字符代替‘%’
使用方法由两种:b.format(a)和format(a,b)。

  1. 基本用法:

    1. 不带编号,即“{}”
    2. 带数字编号,可调换顺序,即“{1}”、“{2}”
    3. 带关键字,即“{a}”、“{tom}”
      1. print('{} {}'.format('hello','world'))
      2. >>hello world
      3. print('{0} {1}'.format('hello','world'))
      4. >>hello world
      5. print('{1} {1} {0}'.format('hello','world'))
      6. >>world world hello
      7. print('{a} {tom} {a}'.format(tom='hello',a='world'))
      8. >>world hello world
  2. 进击用法

    1. < (默认)左对齐、> 右对齐、^ 中间对齐、= (只用于数字)在小数点后进行补齐
    2. 取位数“{:4s}”、”{:.2f}”等
      1. print('{} and {}'.format('hello','world'))
      2. >>hello and world
      3. print('{:10s} and {:>10s}'.format('hello','world'))
      4. >>hello and world
      5. print('{:^10s} and {:^10s}'.format('hello','world'))
      6. >> hello and world
      7. print('{} is {:.2f}'.format(1.123,1.123))
      8. >>1.123 is 1.12
      9. print('{0} is {0:>10.2f}'.format(1.123))
      10. >>1.123 is 1.12
      11. print('{:*>10.2f}'.format(1.123)) #右对齐,小数点后2位,不足的补*
      12. >>******1.12
  3. 多个格式化

‘b’ - 二进制。将数字以2为基数进行输出。
‘c’ - 字符。在打印之前将整数转换成对应的Unicode字符串。
‘d’ - 十进制整数。将数字以10为基数进行输出。
‘o’ - 八进制。将数字以8为基数进行输出。
‘x’ - 十六进制。将数字以16为基数进行输出,9以上的位数用小写字母。
‘e’ - 幂符号。用科学计数法打印数字。用’e’表示幂。
‘g’ - 一般格式。将数值以fixed-point格式输出。当数值特别大的时候,用幂形式打印。
‘n’ - 数字。当值为整数时和’d’相同,值为浮点数时和’g’相同。不同的是它会根据区域设置插入数字分隔符。
‘%’ - 百分数。将数值乘以100然后以fixed-point(‘f’)格式打印,值后面会有一个百分号。

  1. print('{:d}'.format(20))
  2. >>20
  3. print("{:o}".format(20))
  4. >>24
  5. print("{:x}".format(20))
  6. >>14
  7. print('{:e}'.format(20))
  8. >>2.000000e+01
  9. print('{:g}'.format(20.1))
  10. >>20.1
  11. print('{:%}'.format(20))
  12. >>2000.000000%

Print函数


  1. 用逗号分隔输出的字符串

    1. print("a","b",sep=',')
    2. >>a,b
  2. 输出字符串不换行

    1. print('hello')
    2. print('world')
    3. >>hello
    4. >>world
    5. print('hello',end=' ')
    6. print('world')
    7. >>hello world
  3. 格式化

    1. s = 'road'
    2. d = len(s)
    3. print('The length of %s is %d' % (s,d))
    4. >>The length of road is 4

    占位符


Template无疑是一个好东西,可以将字符串的格式固定下来,Template属于string中的一个类,所以要使用的话可以用以下方式调用:
有个特殊的标识符,它的使用具有以下的规则:它的主要实现方式为,它的使用具有以下的规则:它的主要实现方式为xxx,其中xxx是满足python命名规则的字符串,即不能以数字开头,不能为关键字等,如果xxx需要和其他字符串接触时,可用将xxx包裹起来,例如:例如,aaaxxx需要和其他字符串接触时,可用将xxx包裹起来,例如:aaa{xxx}aaa

  1. from string import Template
  2. s = Template('There is $a and ${b}s')
  3. print(s.substitute(a='apple',b='banbana'))
  4. print(s.safe_substitute(a='apple',b='banbana'))
  5. >>There apple and banbanas
  6. >>There apple and banbanas
  • 还可以通过字典来传递数据

    1. from string import Template
    2. s = Template('There is $a and ${b}s')
    3. d = {'a':'apple','b':'banbana'}
    4. print(s.substitute(d))
    5. >>There is apple and banbanas

    注:substitute是一个严肃的方法,如果有key没有输入,那就一定会报错。虽然会很难看,但是可以发现问题。safe_substitute则不会报错,而是将$xxx直接输入到结果字符串中。

    删除多余字符

  • strip

  • lstrip
  • rstrip

传递给lstrip/rstrip/strip的参数被视为一组字符

  1. ' spacious '.lstrip()
  2. >>'spacious '
  3. 'www.example.com'.lstrip('cmowz.')
  4. >>'example.com'

如果想删除一整个字符串,请使用replace或者切片来实现