Python study----------string

#string的内置方法

>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>>

str1 = 'hello,Python'

(1)capitalize()#字符串的第一个字符改为大写

eg:>>> str1.capitalize()

  'Hello,python'

(2)casefold()#把字符串第一个字符改为小写

eg:>>> str1.casefold()
  'hello,python'
(3)center(width[, fillchar])#width -- 字符串的总宽度。fillchar -- 填充字符。

eg:>>> str1.center(12,"8")#需要填充的字符串长度如果小于等于原字符串长度,则返回原字符串,不做改动

'hello,Python'

  >>> str1.center(13,'*')#13大于hello,Pyhon字符串长度12,在前面增加一个“*”
  '*hello,Python'

  >>> str1.center(14,"*")
  '*hello,Python*'

  >>> str1
  'hello,Python'

注:center()方法不改变原字符串内容

(4)count(sub[,start[,end]])#返回sub在字符串里面出现的次数

eg:>>> str1 = 'hello,Python'

  >>> str1.count('l',0,1)
  0
  >>> str1.count('l',0,3)
  1
  >>> str1.count('l')
  2

(5)enconding(encoding = 'UTF-8',errors = 'strict')

   >>>str1 = 'hello,world'

    >>> str1.encode('utf-8')
    b'hello,world'

    >>> str.encode('gbk')
    b'gbk'

(6)、endswith(sub[,start[,end]])# 检查字符串是否以sub字符串结束。

  eg:>>> str1 = 'hello,Python'

    >>> str1.endswith('t')
    False
    >>> str1.endswith('o')
    False
    >>> str1.endswith('n')
    True

未完..........

余生山海远阔,愿你随心所向,随梦所往,随爱所去
原文地址:https://www.cnblogs.com/yigexiaozuanfeng/p/13492934.html