我很黑! 发表于 2018-8-9 08:32:13

python 3 ---字符串方法使用整理

  一、编码部分(结合执行结果进行理解)
  name = "my \tname is {name} and i am {year} old"
  print(name.capitalize())
首字母大写
  print(name.center(50,"-"))
  #打印50个字符,不够的用-补齐,并将chenhl放在中间。
  print(name.encode())
  #将字符串转成二进制,在python中0开头表示8进制,0x或者0X表示16进制,0b或者0B表示二进制。
  print(name.endswith("hl"))
  #判断字符串以什么结尾
  print(name.expandtabs(tabsize=10))
  #自动在字符串中的tab键处补上空格
  print(name.format(name='chenhl',year='30'))
  print(name.format_map({'name':'chenhl','year':'20'}))
  #格式化输入,map 用于字典中
  print(name.find("n"))
  #获取n的索引,即位置,字符串可以切片
  print(name.isalnum())
  #判断变量是否是阿拉伯数字+阿拉伯字符,包含英文字符和0---9数字。是返回true,非则相反。
  print('name'.isalpha())
  #判断变量是否是纯英文字符,是返回true,非则相反。
  print(name.isdecimal())
  print('1.23'.isdecimal())
  print('11'.isdecimal())
  print('1B'.isdecimal())
  #判断是否是十进制
  print(name.isdigit())
  #判断是不是整数
  print('name'.isidentifier())
  #判断是不是一个合法的标识符
  print(name.islower())
  #判断是不是小写
  print(name.isnumeric())
  print('12'.isnumeric())
  print('1.2'.isnumeric())
  #判断是不是只有数字
  print('my name is'.istitle())
  print('My Name Is'.istitle())
  #判断是不是首字母大写
  print('my name is '.isprintable())
  #判断是不是可以打印的文件,tty的文件会返回非。
  print('my future'.isupper())
  #判断是不是都是大写
  print(','.join(['1','2','3']))
  #将列表的内容转成字符串,或将join内容当成一条指令交给os执行。
  print(name.ljust(50,''))
  #保证字符串的长度,不够用在右侧补齐。
  print(name.rjust(50,'-'))
  #保证字符串长度,不够用-在左侧补齐。
  print('ABCD'.lower())
  #把大写变成小写
  print('abcd'.upper())
  #把小写变成大写
  print(' abcd'.lstrip())
  print('\nabcd'.lstrip())
  #去掉左侧的空格或回车。rstrip,去掉右侧的空格或回车,strip去掉两侧的。
  p = str.maketrans('abcdef','123456')
  print('chenhl'.translate(p))
  #将字符串换成后面数字对应的值
  print('chenhl'.replace('h','H',1))
  #将h替换成大写H,count替换几个
  print('chenhl'.rfind('h'))
  #找到值得最后一个位置
  print('ch en hl'.split())
  print('ch en hl'.split('h'))
  #把字符串按照空格或固定字符转成列表
  print('che\nhl'.splitlines())
  #把字符串按照换行转成列表,特别是不同系统的换行
  print('chenhl'.startswith('c'))
  #判断以什么开头的字符串
  print('Hello World'.swapcase())
  #将大写的首字母转换成小写
  print('hello world'.title())
  #将首字母变成大写
  print('hello world'.zfill(20))
  #用零补位,
  二、执行结果
  My name is {name} and i am {year} old
  ------my name is {name} and i am {year} old------
  b'my \tname is {name} and i am {year} old'
  False
  my name is {name} and i am {year} old
  my name is chenhl and i am 30 old
  my name is chenhl and i am 20 old
  4
  False
  True
  False
  False
  True
  False
  False
  True
  True
  False
  True
  False
  False
  True
  True
  False
  1,2,3
  my name is {name} and i am {year} old****
  ------------my name is {name} and i am {year} old
  abcd
  ABCD
  abcd
  abcd
  3h5nhl
  cHenhl
  4
  ['ch', 'en', 'hl']
  ['c', ' en ', 'l']
  ['che', 'hl']
  True
  hELLO wORLD
  Hello World
  000000000hello world
页: [1]
查看完整版本: python 3 ---字符串方法使用整理