str 方法计算整理

by admin on 2019年9月2日

Python_Day_02 str内部方法总括,python_day_02str

刚发轫学习Python,看了一天的字符串内部方法,今后来总结一下。

  •  capitalize(self) 将一句话的首字母变大写,别的字母都变小

1 name = "love PyThon"
2 # capitalize(self)
3 result1 = name.capitalize() #将一句话的首字母变大写,其他字母都变小
4 print('result1:%s'%result1)

打字与印刷结果:

1 result1:Love python

 

  •  casefold(self) 官方表达相比较霸道,确实是相比霸道,全部的字母都成为小写,可是好像用的相当少

1 # casefold(self)
2 name = 'HELLo Python My Name IS RookieJX'
3 result2 = name.casefold()
4 print('result2:%s'%result2)

  打字与印刷结果:

1 result2:hello python my name is rookiejx

 

  •  center(self, width,
    fillchar=None) 那个是将原字符串居中,要是self长度小于width,那么余下的部分就用
    fillchar
    字符填充并,默以为空格,倘使多余的是奇数,那么最终剩余的四个就填充到侧边。个中fillchar只好为单个字符。

1 # center(self, width, fillchar=None)
2 name = 'Python'
3 result3 = name.center(9,"H") 
4 print('result3:%s'%result3)

  打字与印刷结果:

1 result3:HHPythonH

 

  •  count(self, sub, start=None,
    end=None) 查询有些字符或许字符串在self中出现的次数,暗中认可是在全数self上询问,也能够自定义地点

1 # count(self, sub, start=None, end=None)
2 name = 'Hello Python'
3 result4 = name.count("lo",0,40)
4 print('result4:%s'%result4)

  打字与印刷结果:

1 result4:1

 

  • encode(self, encoding=’utf-8′,
    errors=’strict’) 编码为utf-8格式编码,假如出错使用严刻,别的还或然有’ignore’,
    ‘replace’ 等

1 # encode(self, encoding='utf-8', errors='strict')
2 name = 'Hello Python'
3 result5 = name.encode('utf-8','strict') 
4 print('result5:%s'%result5)

  打字与印刷结果:

1 result5:b'Hello Python'

 

  •  endswith(self, suffix, start=None,
    end=None) 以怎么样为终结,私下认可是全部字符串,能够和煦挑选尺寸

1 # endswith(self, suffix, start=None, end=None)
2 name = 'Hello Python'
3 result6 = name.endswith('o',0,3) 
4 print('result6:%s'%result6)

  打字与印刷结果:

1 result6:False

 

  •  expandtabs(self,
    tabsize=8) 将字符串中负有的tab键转变到空格键,默感觉8

1 # expandtabs(self, tabsize=8)
2 result7 = 'hate\tPython'
3 print('origin result7:%s'%result7)
4 result8 = result7.expandtabs() #将字符串中所有的tab键转换成空格键,默认为8
5 print('result8:%s'%result8)
6 result9 = result7.expandtabs(20) #更改默认值
7 print('result9:%s'%result9)

  打字与印刷结果:

1 origin result7:hate    Python
2 result8:hate    Python
3 result9:hate                Python

 

  •  find(self, sub, start=None,
    end=None) 查找有些字符也许字符串在字符串中的下标,默以为搜索全部字符串

1 # find(self, sub, start=None, end=None)
2 name = 'Hello Python'
3 result10 = name.find('P') #查找某个字符或者字符串在字符串中的下标,默认为查找全部字符串
4 print('result10:%s'%result10)
5 result11 = name.find('P',0,4) #可以自定义查找范围,如果没有就返回 -1
6 print('result11:%s'%result11)

  打字与印刷结果:

1 result10:6
2 result11:-1

 

  •  format(*args,
    **kwargs) 好像很暴力的模范,格式化字符串,有为数十分多用法

 1 # format(*args, **kwargs)
 2 # 好像很暴力的样子,格式化字符串,有很多用法
 3 # 1.可以使用 {} 用作占位符 这里分割的时候需要使用 . 不是用 , 这点需要注意
 4 print('I am {},I {} '.format('rookieJX','Love Python'))
 5 # 2.也可以使用 {0} {1}等样式的占位符
 6 print('I am {1},I {0}'.format('Love Python','rookieJX'))
 7 # 3.还可以使用变量形式的占位符
 8 print('My job is {job}'.format(job = 'IT'))
 9 # 4.还可以混合使用
10 print('I am {1},My job is {job}'.format('haha','rookieJX',job = 'IT'))

  打字与印刷结果:

1 I am rookieJX,I Love Python 
2 I am rookieJX,I Love Python
3 My job is IT
4 I am rookieJX,My job is IT

 

  •  format_map(self,
    mapping) 最近明白的还非常少

 

  •  index(self, sub, start=None,
    end=None) 类似于find方法,可是当要搜索的字符串不在查找的字符串中的话会报错

1 # index(self, sub, start=None, end=None)
2 name = 'Hello Python'
3 result12 = name.index('P') # 类似于find方法,但是当要查找的字符串不在查找的字符串中的话会报错
4 print('result12:%s'%result12)
5 result13 = name.index('P',0,10) # 还可以自定义限制查找的范围
6 print('result13:%s'%result13)

  打字与印刷结果:

1 result12:6
2 result13:6

 

  •  isalnum(self) 字符串中至少有贰个字符,并且具备的字符都以字母或许数字重返为True
    不然再次来到为 False (空格也回到False)

1 # isalnum(self)
2 name = 'Hello Python'
3 result14 = name.isalnum() # 字符串中至少有一个字符,并且所有的字符都是字母或者数字返回为True 否则返回为 False (空格也返回False)
4 print('result14:%s'%result14)

  打字与印刷结果:

1 result14:False

 

  •  is阿尔法(self) 字符串中最少有一个是字符,而且有着的字符都以字母再次回到为
    True 否则重回为 False (空格也回到False)

1 # isalpha(self)
2 name = 'Hello Python'
3 result15 = name.isalpha()
4 print('result15:%s'%result15) # 字符串中至少有一个是字符,并且所有的字符都是字母返回为 True 否则返回为 False (空格也返回False)

  打字与印刷结果:

1 result15:False

 

  •  isdecimal(self) 判别字符串是还是不是是十进制整数,假使不是回到为
    False ,如若不是字符串就能报错

1 # isdecimal(self)
2 namedeclimal = "324.2" # 判断字符串是否是十进制整数,如果不是返回为 False ,如果不是字符串就会报错
3 result16 = namedeclimal.isdecimal()
4 print('result16:%s'%result16)

  打字与印刷结果:

1 result16:False
  •  isdigit(self) 剖断字符串中是或不是只包涵数字

1 # isdigit(self)
2 namedeclimal = "324.2"
3 result17 = namedeclimal.isdigit() # 判断字符串中是否只包含数字
4 print('result17:%s'%result17)

  打印结果:

1 result17:False

 

  •  isidentifier(self) 判别字符串是不是是关键字

1 # isidentifier(self)
2 result18 = 'str'.isidentifier() # 判断字符串是否是关键字
3 print('result18:%s'%result18)

  打字与印刷结果:

1 result18:True

 

  •  islower(self) 字符串中足足有三个字符,字符整体为小写就重返True

1 # islower(self)
2 name = 'Hello Python'
3 result19 = name.islower() # 字符串中至少有一个字符,字符全部为小写就返回 True
4 print('result19:%s'%result19)

  打字与印刷结果:

1 result19:False

 

  •  isnumeric(self) 字符串中只要全是数字字符重返True 貌似跟 isdecimal 大致,权且还从未察觉有怎样不一样的用法

1 # isnumeric(self)
2 result20 = '4232'.isnumeric() # 字符串中如果全部都是数字字符返回 True 貌似跟 isdecimal 差不多,暂时还没有发现有什么不同的用法
3 print('result20:%s'%result20)

  打字与印刷结果:

1 result20:True

 

  •  isprintable(self) 推断字符串中具有字符是还是不是是可知状态

1 # isprintable(self)
2 result21 = 'I\aPython'.isprintable() # 判断字符串中所有字符是否是可见状态
3 print('result20:%s'%result21)

  打字与印刷结果:

1 result20:False

 

  •  isspace(self) 字符串中纵然只至少有四个字符,而且全体为空格时
    重临为True

1 # isspace(self)
2 result22 = '   '.isspace() # 字符串中如果只至少有一个字符,并且全部为空格时 返回为True
3 print('result22:%s'%result22)

  打字与印刷结果:

1 result22:True

 

  •  istitle(self) 字符串是不是为标题格式
    正是各种单词首字母都是大写

1 # istitle(self)
2 result23 = 'This Is Python'.istitle() # 字符串是否为标题格式 就是每个单词首字母都是大写
3 print('result23:%s'%result23)

  打字与印刷结果:

1 result23:True

 

  •  isupper(self) 字符串至少有一个字符
    剖断字符是还是不是是大写 固然是大写就赶回 True
    (只会咬定在这之中的塞尔维亚共和国语字符,特殊符号,数字不会推断)

1 # isupper(self)
2 result24 = 'NAME.803'.isupper() # 字符串至少有一个字符 判断字符是否是大写 如果是大写就返回 True (只会判断其中的英文字符,特殊符号,数字不会判断)
3 print('result24:%s'%result24)

  打字与印刷结果:

1 result24:True

 

  •  join(self,
    iterable) 将self字符串用iterable打垮,每一个多个字符串之间插入
    iterable 字符串

1 # join(self, iterable)
2 name = 'Hello Python'
3 result25 = name.join('Hello World') # 将iterable字符串打散,每个两个字符串之间插入 string 字符串
4 print('result25:%s'%result25)

  打字与印刷结果:

1 result25:HHello PythoneHello PythonlHello PythonlHello PythonoHello Python Hello PythonWHello PythonoHello PythonrHello PythonlHello Pythond

 

  •  ljust(self, width,
    fillchar=None) 原字符串左对齐,总字符串长度为自定义长度,侧边填充字符
    默许为空格 就算定义长度小于元字符串长度,则不会开展操作

1 # ljust(self, width, fillchar=None)
2 name = 'Hello Python'
3 result26 = name.ljust(23,'H') # 原字符串左对齐,总字符串长度为自定义长度,右边填充字符 默认为空格 如果定义长度小于元字符串长度,则不会进行操作
4 print('result26:%s'%result26)

  打字与印刷结果:

1 result26:Hello PythonHHHHHHHHHHH

 

  •  lower(self) 拷贝一份原有的字符串,并将之变成小写
    貌似跟casefold效果等同的

1 # lower(self)
2 name = 'Hello Python'
3 result27 = name.lower() # 拷贝一份原有的字符串,并将之变为小写 貌似跟casefold效果一样的
4 print('result27:%s'%result27)

  打字与印刷结果:

1 result27:hello python

 

  •  lstrip(self,
    chars=None) 暗中认可截掉字符串左边的空格,假若自定义字符,那么字符必需是从字符串的启幕本事截取成功

1 # lstrip(self, chars=None)
2 result28 = '   Hello'.lstrip() # 默认截掉字符串左边的空格,如果自定义字符,那么字符必须是从字符串的开始才能截取成功
3 print('result28:%s'%result28)
4 
5 result29 = 'Hello'.lstrip('H') # 默认截掉字符串左边的空格,如果自定义字符,那么字符必须是从字符串的开始才能截取成功
6 print('result29:%s'%result29)

  打字与印刷结果:

1 result28:Hello
2 result29:ello

 

  •  maketrans(self, *args,
    **kwargs) 营造替换映射表,首先创设映射对应表格,映射前为intab,映射后为outtab.然后创设对应表格maketrans,最终起初转变

1 # maketrans(self, *args, **kwargs)
2 intab = "aeiou"
3 outtab = "12398"
4 intro = "hello python in my heart"
5 result29 = str.maketrans(intab,outtab)
6 result30 = intro.translate(result29) # 构建替换映射表,首先构建映射对应表格,映射前为intab,映射后为outtab.然后构建对应表格maketrans,最后开始转换
7 print('intro:%s'%result30)

  打字与印刷结果:

1 intro:h2ll9 pyth9n 3n my h21rt

 

  •  partition(self,
    sep) 依据钦命字符串来划分原字符串,即使原字符串存在钦赐字符串,结果为
    分割侧面原字符串,钦定字符串,分割后右字符串…假使不设有钦定字符串则赶回原字符串,只会分开出现的第三个职位

1 # partition(self, sep)
2 test = 'Hello Python , Hello Python ,Hello World'
3 result31 = test.partition('P') # 根据指定字符串来分割原字符串,如果原字符串存在指定字符串,结果为 分割左边原字符串,指定字符串,分割后右字符串...如果不存在指定字符串则返回原字符串,只会分割出现的第一个位置
4 print('result31:',result31)

  打字与印刷结果:

1 result31: ('Hello ', 'P', 'ython , Hello Python ,Hello World')

 

  •  replace(self, old, new,
    count=None) 替换字符串.最大不超过多少次

1 # replace(self, old, new, count=None)
2 result32 = 'love python love python love python love python love python '.replace('love','hate',3) # 替换字符串.最大不超过多少次
3 print('result32:%s'%result32)

  打字与印刷结果:

1 result32:hate python hate python hate python love python love python 

 

  •  rfind(self, sub, start=None,
    end=None) 查找内定字符串在原字符串中最侧面的职位,默感到一体字符串

1 # rfind(self, sub, start=None, end=None)
2 result33 = 'love python love '.rfind('lo') # 查找指定字符串在原字符串中最右边的位置,默认为整个字符串
3 print('result33:%s'%result33)

  打字与印刷结果:

1 result33:12

 

  •  rindex(self, sub, start=None,
    end=None) 查找钦命字符串在原字符串中最左边的职分,默以为一体字符串,跟rfind效果大致,然而只要找不到就能报错

1 # rindex(self, sub, start=None, end=None)
2 result34 = 'love python love '.rindex('lo') # 查找指定字符串在原字符串中最右边的位置,默认为整个字符串,跟rfind效果差不多,但是如果找不到就会报错
3 print('result34:%s'%result34)

  打字与印刷结果:

1 result34:12

 

  •  rjust(self, width,
    fillchar=None) 再次来到贰个右边对其的原字符串,默许用空格对其,能够自定义字符,可是一旦是自定义字符串的话,那么自定义的字符串必得能被剩下的空格整除,不然就能够报错

1 # rjust(self, width, fillchar=None)
2 name = "love PyThon"
3 result35 = name.rjust(50,'O') # 返回一个右边对其的原字符串,默认用空格对其,可以自定义字符,但是如果是自定义字符串的话,那么自定义的字符串必须能被多余的空格整除,否则就会报错
4 print('result35:%s'%result35)

  打字与印刷结果:

1 result35:OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOlove PyThon

 

  •  rpartition(self,
    sep) 类似于partition 只可是是从侧边开端查找

1 # rpartition(self, sep)
2 test2 = 'Hello Python ,Hello Python , Hello WoPrld'
3 result36 = test2.rpartition('P') # 类似于partition 只不过是从右边开始查找
4 print('result36:',result36)

  打字与印刷结果:

1 result36: ('Hello Python ,Hello Python , Hello Wo', 'P', 'rld')

 

  •  split(self, sep=None,
    maxsplit=-1) 依据钦定字符串来分割字符串,假诺钦点最大分割字符串,那么久分割钦命次数,假设不钦赐默感觉-1约等于最大

1 # split(self, sep=None, maxsplit=-1)
2 test3 = 'Hello Python ,Hello Python , Hello WoPrld'
3 result37 = test3.split('P',2) # 根据指定字符串来分割字符串,如果指定最大分割字符串,那么久分割指定次数,如果不指定默认为-1也就是最大
4 print('result37:',result37)

  打字与印刷结果:

1 result37: ['Hello ', 'ython ,Hello ', 'ython , Hello WoPrld']

 

  •  splitlines(self,
    keepends=None) 按照行(‘\r’, ‘\r\n’,
    \n’)分隔,再次来到三个包含各行作为成分的列表,假使参数 keepends 为
    False,不含有换行符,要是为 True,则保留换行符.暗许为False

1 # splitlines(self, keepends=None)
2 test4 = 'Hello\r Pyth\non ,Hel\r\nlo Python , Hello WoPrld'
3 result38 = test4.splitlines(True) # 按照行('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符.默认为False
4 print('result38:',result38)

  打印结果:

1 result38: ['Hello\r', ' Pyth\n', 'on ,Hel\r\n', 'lo Python , Hello WoPrld']

 

  •  startswith(self, prefix, start=None,
    end=None) 查看是不是 以钦命字符串为发端 并得以钦赐范围

1 # startswith(self, prefix, start=None, end=None)
2 test5 = 'Hello\r Pyth\non ,Hel\r\nlo Python , Hello WoPrld'
3 result39 = test5.startswith('ell',0,30) # 查看是否 以指定字符串为开头 并可以指定范围
4 print('result39:',result39)

  打字与印刷结果:

1 result39: False

 

  •  strip(self,
    chars=None) 对字符串试行去掉左右两侧的空格,默许为撤销空格,能够安装为钦命字符

1 # strip(self, chars=None)
2 test6 = 'H    Hello Python ,Hello Python , Hello WoPrld    H'
3 result40 = test6.strip('H') # 对字符串执行 去掉左右两边的空格,默认为取消空格,可以设置为指定字符
4 print('result40:',result40)

  打字与印刷结果:

1 result40:     Hello Python ,Hello Python , Hello WoPrld    

 

  •  swapcase(self) 翻转字符串中的大小写

1 # swapcase(self)
2 test7 = 'H    Hello Python ,Hello Python , Hello WoPrld    H'
3 result41 = test7.swapcase() # 翻转字符串中的大小写
4 print('result41:',result41)

  打印结果:

1 result41: h    hELLO pYTHON ,hELLO pYTHON , hELLO wOpRLD    h

 

  •  title(self) 将字符串中每种单词首字母置为题写

1 # title(self)
2 test8 = 'H    hello python ,hello python , hello woPrld    H'
3 result42 = test8.title() # 将字符串中每个单词首字母置为大写
4 print('result42:',result42)

  打字与印刷结果:

1 result42: H    Hello Python ,Hello Python , Hello Woprld    H

 

  •  translate(self, table)  与maketrans(self, *args,
    **kwargs)合营使用 

 

  •  upper(self) 将字符串退换为题写

1 # upper(self)
2 test9 = 'H    hello python ,hello python , hello woPrld    H'
3 result43 = test9.upper() # 将字符串改变为大写
4 print('result43:',result43)

  打字与印刷结果:

1 result43: H    HELLO PYTHON ,HELLO PYTHON , HELLO WOPRLD    H

 

  •   zfill(self,
    width) 左侧对齐,右边填充数字0,长度为自定义

1 # zfill(self, width)
2 test10 = 'H    hello python ,hello python , hello woPrld    H'
3 result44 = test10.zfill(70) # 右边对齐,左边填充数字0,长度为自定义
4 print('result44:',result44)

  打字与印刷结果:

1 result44: 0000000000000000000H    hello python ,hello python , hello woPrld    H

 

str内部方法总计,python_day_02str
刚开端学习Python,看了一天的字符串内部方法,今后来计算一下。
capitalize(self) 将一句话的首字母…

刚起头读书Python,看了一天的字符串内部方法,未来来计算一下。

代码

#!/usr/bin/env python
#Python 3.7.0 字符串常用方法
__author__ = "lrtao2010"

#capitalize 将字符串的首字符改为大写
# a = "lrtao"
# v = a.capitalize()
# print(v)
# Lrtao

#casefold 将字符串所有字符改为小写,功能强大
# a = "LrTao"
# v = a.casefold()
# print(v)
# lrtao

#lower 将字符串所有字符改为小写
# a = "LrTao"
# v = a.lower()
# print(v)
# lrtao

#upper 将字符全部转成大写
# a = "LrTao"
# v = a.upper()
# print(v)
# LRTAO

#center(self, width, fillchar=None) 内容居中,width:总长度(当width<len(s)时没有效果);
#                                   fillchar:空白处填充内容,默认无
# a = "lrtao"
# v = a.center(20,'*')
# print(v)
# *******lrtao********

#ljust(self, width: int, fillchar: str = ...)内容左对齐,右侧填充,不指定默认空白
# a = "lrtao"
# v1 = a.ljust(20,'*')
# v2 = a.ljust(20)
# print(v1)
# print(v2)
# lrtao***************
# lrtao

#rjust(self, width: int, fillchar: str = ...)内容右对齐,左侧填充,不指定默认空白
# a = "lrtao"
# v1 = a.rjust(20,'*')
# v2 = a.rjust(20)
# print(v1)
# print(v2)
# ***************lrtao
#                lrtao

# zfill(self, width: int) z指zero,用0将字符填充到指定长度(左侧填充)
# a = "test"
# v = a.zfill(20)
# print(v)
# 0000000000000000test

# a = "test"
# v1 = a.rjust(20,'0')
# print(v1)
# 0000000000000000test

#count(self, sub, start=None, end=None) 统计子序列在字符串里出现的次数,包括start,不包括end

# a = "lilelili"
# v1 = a.count('li')
# v2 = a.count('li',1)
# v3 = a.count('li',1,6)
# print(v1,v2,v3)
# 3 2 1
#encode(encoding='utf-8',errors='strict')  以encoding指定的编码格式对字符串进行编码
# a = "lilei"
# v = a.encode(encoding='utf-8')
# print(v)
# b'lilei'
#

#endswith(self, suffix, start=None, end=None)是否以指定字符串结束,返回值为布尔值

# a = "hello"
# v1 = a.endswith('o')
# v2 = a.endswith('l')
# v3 = a.endswith('lo')
# v4 = a.endswith('e',0,2)

# print(v1,v2,v3,v4)
# True False True True

#startswith(self, prefix: Union[str, Tuple[str, ...]], start: Optional[int] = ...,end: Optional[int] = ...)
#是否以指定字符串开始,返回值为布尔值
# a = "hello"
# v1 = a.startswith('h')
# v2 = a.startswith('e')
# v3 = a.startswith('he')
# v4 = a.startswith('e',1,3)
#
# print(v1,v2,v3,v4)
# True False True True

#expandtabs
# 按指定的宽度对字符串进行分割,遇到tab字符(\t)转化为空格,默认以8个字符位置分割
#可用作格式化
# a = '1234\t56\t7890\t0\t123'
# v = a.expandtabs(6)
# u_e_p = 'username\temail\tpasswd\nlrtao2010\tlrtao2010@163.com\t123456\nlrtao\tlrtao@163.com\t123'
# v1 = u_e_p.expandtabs(30)
# print(v)
# print(v1)
# 1234  56    7890  0     123
# username                      email                         passwd
# lrtao2010                     lrtao2010@163.com             123456
# lrtao                         lrtao@163.com                 123

# find(self, sub, start=None, end=None) 返回首次找到子序列的位置,如果没找到,返回 -1
# a = 'lilei'
# v1 = a.find('l')
# v2 = a.find('l',2)
# v3 = a.find('lei',2,4)
# print(v1,v2,v3)
# 0 2 -1

#index(self, sub, start=None, end=None)返回首次找到子序列的位置,如果没找到程序会报异常
# a = 'lilei'
# v = a.index('ll')
# print(v)
# Traceback (most recent call last):
#     v = a.index('ll')
# ValueError: substring not found

#rfind(self, sub: str, __start: Optional[int] = ..., __end: Optional[int] = ...)
#返回指定子串的最大索引,如果没找到则返回-1,可以指定要开始和结束位置。
# a = 'lilililili'
# v1 = a.rfind('li')
# v2 = a.rfind('li',9)
# v3 = a.rfind('li',2,4)
# print(v1,v2,v3)
# 8 -1 2

#rindex(self, sub: str, __start: Optional[int] = ..., __end: Optional[int] = ...)
#返回指定子串的最大索引,如果没找到则抛异常,可以指定要开始和结束位置。
# a = 'lilililili'
# v1 = a.rindex('li')
# v2 = a.rindex('li',9)
# v3 = a.rindex('li',2,4)
# print(v1)
# print(v2)
# print(v3)
# v2 = a.rindex('li',9)
# ValueError: substring not found
#
# Process finished with exit code 1


#format 字符串格式化
# a = 'hello ,{name}!hello ,{name2} !'
# v = a.format(name='lilei',name2='tom')
# print(v)
# hello ,lilei!hello ,tom !

# a = 'hello,{0}! hello,{1}!'
# v = a.format('lilei','tom')
# print(v)
# hello,lilei! hello,tom!

#format_map(self, mapping) 和format相似,参数为字典形式
# a = 'hello ,{name}!hello ,{name2} !'
# v = a.format_map({'name2':'lilei','name':'tom'})
# print(v)
# hello ,tom!hello ,lilei !

#isalnum 是否只包含字母或数字,返回值为布尔值
# a = 'lsL123'
# b = 'ls'
# c = 'LS'
# d = '123'
# e = 'ls@'
# v1 = a.isalnum()
# v2 = b.isalnum()
# v3 = c.isalnum()
# v4 = d.isalnum()
# v5 = e.isalnum()
# print(v1,v2,v3,v4,v5)
# True True True True False

#isalpha 字符串是否全部是字母
# a = 'lsL123'
# b = 'ls'
# c = 'LS'
# d = 'Ls'
# e = 'ls@'
# v1 = a.isalpha()
# v2 = b.isalpha()
# v3 = c.isalpha()
# v4 = d.isalpha()
# v5 = e.isalpha()
# print(v1,v2,v3,v4,v5)
# False True True True False

#isascii Return True if all characters in the string are ASCII, False otherwise.
# a = '12ls er$%^&*()'
# b = '中'
# v1 = a.isascii()
# v2 = b.isascii()
# print(v1,v2)
# True False

#isdecimal 字符串是否是十进制字符串
# a = '1234567890'
# b = 'A0'
# v1 = a.isdecimal()
# v2 = b.isdecimal()
# print(v1,v2)
# True False

#isdigit 如果字符串是数字字符串,则返回True,否则返回False。
# isdecimal() 如果字符串是数字字符串,则返回True,否则返回False。
#isnumeric 如果字符串是数字字符串,则返回True,否则返回False

# num = "一"
# v1 = num.isdigit()
# v2 = num.isdecimal()
# v3 = num.isnumeric()
# print(v1,v2,v3)
# False False True

# num = "Ⅰ" #罗马数字1
# v1 = num.isdigit()
# v2 = num.isdecimal()
# v3 = num.isnumeric()
# print(v1,v2,v3)
# False False True

# num = "1"
# v1 = num.isdigit()
# v2 = num.isdecimal()
# v3 = num.isnumeric()
# print(v1,v2,v3)
# True True True

# isdigit()
# True: Unicode数字,byte数字(单字节),全角数字(双字节),罗马数字
# False: 汉字数字
# Error: 无
# isdecimal()
# True: Unicode数字,全角数字(双字节)
# False: 罗马数字,汉字数字
# Error: byte数字(单字节)
# isnumeric()
# True: Unicode数字,全角数字(双字节),罗马数字,汉字数字
# False: 无
# Error: byte数字(单字节)


#isidentifier 判断字符串是否包含python的保留字
# v1 = 'def'.isidentifier()
# v2 = 'aaa'.isdecimal()
# print(v1,v2)
# True False

#islower 字符串中不能出现大写字母,并且至少有一个小写字母
# a = 'ls12#3'
# b = 'Ls'
# c = '1234s'
# d = 'LS'
# v1 = a.islower()
# v2 = b.islower()
# v3 = c.islower()
# v4 = d.islower()
# print(v1,v2,v3,v4)
# True False True False

#isprintable 检查字符串中是否包含不可安原型显示的内容
# a = 'test'
# b = 't\test' #\t在print时不能显示为\t
# c = 'test\n' #\n在print时不能显示为\n
# v1 = a.isprintable()
# v2 = b.isprintable()
# v3 = c.isprintable()
# print(v1,v2,v3)
# True False False


#isspace 判断字符串是否全部是空格
# a = ''
# b = ' '
# c = 'a b'
# v1 = a.isspace()
# v2 = b.isspace()
# v3 = c.isspace()
# print(v1,v2,v3)
# False True False

#title  标题格式(可以理解为单词首字母大写,其它字符小写)
# a = 'this is title'
# v = a.title()
# print(v)
# This Is Title

#istitle 判断是否是标题格式(可以理解为首字母是否大写)
# a = "this is title"
# b = "This is title"
# c = "This Is title"
# d = "This Is Title"
# v1 = a.istitle()
# v2 = b.istitle()
# v3 = c.istitle()
# v4 = d.istitle()
# print(v1,v2,v3,v4)
# False False False True

#isupper 判断字母是否全部是大写
# a = 'lsL123'
# b = 'LSF123'
# c = 'LSF'
# d = 'LS F'
# v1 = a.isupper()
# v2 = b.isupper()
# v3 = c.isupper()
# v4 = d.isupper()
# print(v1,v2,v3,v4)
# False True True True

#join(self, iterable: Iterable[str])返回一个用指定分隔符分隔的字,
#                                   或者是将指定字符加入到另一个字符中。
# a = 'iamtom'
# v1 = '.'.join(a)
# v2 = '#'.join(a)
# print(v1)
# print(v2)
# i.a.m.t.o.m
# i#a#m#t#o#m

#partition(self, sep: str) 按照指定的字符将字符串分为前中后三部分,从左侧开始
# a = "iamtom"
# v1 = a.partition("i")
# v2 = a.partition('am')
# v3 = a.partition('om')
# v4 = a.partition('som')
# print(v1)
# print(v2)
# print(v3)
# print(v4)
# ('', 'i', 'amtom')
# ('i', 'am', 'tom')
# ('iamt', 'om', '')
# ('iamtom', '', '')

#rpartition(self, sep: str) 与partition一样,但是从右边开始
# a = "iamtom"
# v1 = a.rpartition("i")
# v2 = a.rpartition('am')
# v3 = a.rpartition('tom')
# v4 = a.rpartition('som')
# print(v1)
# print(v2)
# print(v3)
# print(v4)
# ('', 'i', 'amtom')
# ('i', 'am', 'tom')
# ('iam', 'tom', '')
# ('', '', 'iamtom')


#replace(self, old: str, new: str, count: int = ...) 替换字符,不指定次数默认全部替换
# a = 'iamtomtomtom'
# v1 = a.replace('m','i')
# v2 = a.replace('m','i',1)
# print(a)
# print(v1)
# print(v2)
# iamtomtomtom
# iaitoitoitoi
# iaitomtomtom



#split(self, sep: Optional[str] = ..., maxsplit: int = ...)
#按指定字符串从左侧开始进行切割,可以指定切割次数(不指定全部切割)

# a = 'iamtomtom'
# v1 = a.split('m')
# v2 = a.split('m',2)
# print(v1)
# print(v2)
# ['ia', 'to', 'to', '']
# ['ia', 'to', 'tom']

#rsplit(self, sep: Optional[str] = ..., maxsplit: int = ...)
#按指定字符串从右侧开始进行切割,可以指定切割次数(不指定全部切割)
# a = 'iamtomtom'
# v1 = a.rsplit('m')
# v2 = a.rsplit('m',2)
# print(v1)
# print(v2)
# ['ia', 'to', 'to', '']
# ['iamto', 'to', '']

#strip(self, chars: Optional[str] = ...)
#移除两侧(最外侧)指定字符串,默认移除空格,以指定多个字符

# a = ' i am tom m'
# v1 = a.strip()
# v2 = a.strip('m')
# v3 = a.strip('ap')
# v4 = a.strip('am')
# print(v1)
# print(v2)
# print(v3)
# print(v4)
# i am tom m
#  i am tom
#  i am tom m
#  i am tom

#rstrip(self, chars: Optional[str] = ...)
#移除右侧指定字符

# a = ' i am tom m'
# v1 = a.rstrip()
# v2 = a.rstrip('m')
# v3 = a.rstrip('ap')
# v4 = a.rstrip('am')
# print(v1)
# print(v2)
# print(v3)
# print(v4)
 # i am tom m
 # i am tom
 # i am tom m
 # i am tom

#lstrip 移除左侧空白
# a = ' i am tom m '
# v1 = a.lstrip()
# print(v1)
# i am tom m


 #splitlines(self, keepends: bool = ...)
 #按换行符\n切割,如果没指定keepends=True,则会将其从结果中移除
# a = "this is test1\n this is test2"
# v1 = a.splitlines(keepends=True)
# v2 = a.splitlines()
# print(v1)
# print(v2)
# ['this is test1\n', ' this is test2']
# ['this is test1', ' this is test2']

#swapcase 大小写转换
# a = 'This Is Test 01'
# v = a.swapcase()
# print(v)
# tHIS iS tEST 01

#translate(self, table: Optional[bytes], delete: bytes = ...)
#translate() 方法根据参数table给出的表(包含 256 个字符)转换字符串的字符,
# 要过滤掉的字符放到 deletechars 参数中

# intab = "aeiou"
# outtab = "12345"
# trantab = str.maketrans(intab, outtab)  # 制作翻译表
# str = "this is string example....wow!!!"
# print(str.translate(trantab))
# th3s 3s str3ng 2x1mpl2....w4w!!!

# 制作翻译表
# bytes_tabtrans = bytes.maketrans(b'abcdefghijklmnopqrstuvwxyz', b'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
#
# # 转换为大写,并删除字母o
# print(b'runoob'.translate(bytes_tabtrans, b'o'))
# b'RUNB'

################################################################################################
#字符串也有索引的概念
# a = 'index'
# v1 = a[0]
# v2 = a[3]
# v3 = a[-1]
# v4 = a[0:4]
# print(v1,v2,v3,v4)
# i e x inde

#len()
#
# a = 'abc'
# b = '测试'
# v1 = len(a)
# v2 = len(b)
# print(v1,v2)
# 3 2

#对字符串可以直接使用for、while 循环

# a = '测试'
#
# for i in a:
#     print(i)
# 测
# 试
#
# index = 0
# while index < len(a):
#     print(a[index])
#     index += 1
# 测
# 试

str字符串常用方法,str字符串

  •  capitalize(self) 将一句话的首字母变大写,其余字母都变小

    1 name = “love PyThon”
    2 # capitalize(self)
    3 result1 = name.capitalize() #将一句话的首字母变大写,别的字母都变小
    4 print(‘result1:%s’%result1)

#str内部功能
name='  aK am\til.L iu'
age=18
num=-11
ab='#'
ac=('1','2','3','4','5','6','7')
print(dir(name))
print(name.capitalize())#capitalize(self):首字母大写
print(name.center(30,'#'))#center(self, width, fillchar=None): 内容居中,width:总长度;fillchar:空白处填充内容,默认无
print(name.count('i'))#count(self, sub, start=None, end=None):子序列个数
'''
decode(self, encoding=None, errors=None):解码
encode(self, encoding=None, errors=None):编码,针对unicode
'''
print(name.endswith('u'))#endswith(self, suffix, start=None, end=None):是否以xxx结束 startswith(self, prefix, start=None, end=None):是否起始
print(name)
print(name.expandtabs(3))#expandtabs(self, tabsize=None):将tab转换成空格,默认一个tab转换成8个空格
print(name.find('i'))#find(self, sub, start=None, end=None):寻找子序列位置,如果没找到,返回 –1
print(name.find('b'))
#format(*args, **kwargs):字符串格式化,动态参数,讲函数式编程时细说
print(name.index('il'))#index(self, sub, start=None, end=None): 子序列位置,如果没找到,报错
print(name.isalnum())#
'''
isalnum(self): 是否是字母和数字
isalpha(self):是否是字母
isdigit(self):是否是数字
islower(self): 是否小写
translate(self, table, deletechars=None):转换,需要先做一个对应表,最后一个表示删除字符集合
'''
print(ab.join(ac))#join(self, iterable):连接
print(name.ljust(30,'$'))#ljust(self, width, fillchar=None):内容左对齐,右侧填充    zfill(self, width):方法返回指定长度的字符串,原字符串右对齐,前面填充0。
print(name.lower())#lower(self):变小写     swapcase(self):大写变小写,小写变大写
print(name.lstrip())#lstrip(self, chars=None):移除左侧空白      strip(self, chars=None):移除两端空白
print(name.partition('m'))#partition(self, sep):分割,前,中,后三部分
print(name.replace('am', 'qqqqqq'))#replace(self, old, new, count=None):替换
print(name.split())#split(self, sep=None, maxsplit=None):分割, maxsplit最多分割几次
print(name.splitlines())#splitlines(self, keepends=False):根据换行分割

 

    字符串是编制程序中常用的种类,字符型在内存中是以单个格局储存的,譬喻name

“alex”,在内部存款和储蓄器中存放的方式为[“a”,”l”,”e”,”x”],因而大家能够利用列表的过多职能来操作字符串,因为小编起来的时候平素在想干什么字符串能够运用切条,能够有目录,开端的时候一贯不知底,后来精晓了Python字符串的囤积情势之后才清楚为何存在那一个措施。上面大家来探问字符串类型中包含那多少个方法:

   
在Python中有个别措施上面有注释,那是因为这个措施应用Python本人编排的,大家领略Python中好多是一贯调用C语言中的方法,看不到的那个是C语言中的方法。

    1.capitalize(self)

    def capitalize(self): # real signature unknown; restored from
__doc__
    ”””
    S.capitalize() -> str
        首字母大写,只是第二个位居第一位第壹个首字母大写
    Return a capitalized version of S, i.e. make the first
character
    have upper case and the rest lower case.
    ”””
    return “”

   
capitalize(self)是居首首字母大写,咱们清楚还会有叁个措施title(),上边来相比那三个艺术的差别点:

    >>> name = “alex is sb”
  >>> name.capitalize()
  ’Alex is sb’
  >>> name.title()
  ’Alex Is Sb’

   
从下面可以旁观,capitalize(self)是位居第一位首字母大写,别的字母非常小写;而title(self)方法是具备单词的首字母都大写,那几个在用的时候要通晓是要求那么字母大写。

    2.casefold(self)

    def casefold(self): # real signature unknown; restored from
__doc__
    ”””
    S.casefold() -> str
        全数首字母小写,等价于lower()
    Return a version of S suitable for caseless comparisons.
    ”””
    return “”

    casefold(self)是将大写字母转化为小写,等价于lower(self),实举个例子下:

    >>> name = “ALEX Is SB”
  >>> name.casefold()
  ’alex is sb’
  >>> name
  ’ALEX Is SB’
  >>> name.lower()
  ’alex is sb’

  3.center(self,width,fillchar=None)

    def center(self, width, fillchar=None): # real signature unknown;
restored from __doc__
    ”””
    S.center(width[, fillchar]) -> str
       
“””center(self,width,fillchar=None)是将字符串放到中间,两边加上大肆符号,暗许空格”””
    Return S centered in a string of length width. Padding is
    done using the specified fill character (default is a space)
    ”””
    return “”

   
center(self,width,fillchar=None),美化格式,把self放到中间,钦命大肆长度的字符,空白处用字符填充,暗中同意时间和空间字符。示比方下:

    >>> name = “您好”
  >>> name.center(12)
  ’     您好     ‘
  >>> name.center(12,”-“)
  ’—–您好—–‘

    4.__format__(self,format_spec)

    def __format__(self, format_spec): # real signature unknown;
restored from __doc__
    ”””
    S.__format__(format_spec) -> str
        字符串的格式化
    Return a formatted version of S as described by format_spec.
    ”””
    return “”

   
__format__(self,format_spec)字符串实行格式化,根据我们要求的格式举行字符串格式化操作。详细可参照()

    >>> tp1 = “My name is {0},and I am {1} years old,I am
{2}”

  >>> tp1.format(“Alex”,”18″,”sb”)

    ‘My name is Alex,and I am 18 years old,I am sb’

    >>> tp2 = “I am {1} years old,my name is {2},and I am
{0}.”

  >>> tp2.format(“sb”,”18″,”Alex”)
  ’I am 18 years old,my name is Alex,and I am sb.’
   
这种办法也足以用在字符串的拼接上边,使用字符串的format()方法,在{}大括号中定义索引,告诉Python把哪些值传给索引地方。

    5.__getattribute__(self,*args,**kwargs)

    def __getattribute__(self, *args, **kwargs): # real
signature unknown
    ””” Return getattr(self, name). “””

        “””反射的时候用的”””
    pass

    6.__getitem__(self,*args,**kwargs)

    def __getitem__(self, *args, **kwargs): # real signature
unknown
    ””” Return self[key]. “””

    ”””获得字符串低端个要素,等价于self[key]”””
    pass  

   
正是获取字符串中第多少个职责的字符,大家通晓字符串在内部存款和储蓄器中是以列表方式积存的,因而能够使用索引来获取单个字符,实举个例子下:

    >>> name = “Alexissb”
  >>> name.__getitem__(2)
  ’e’
  >>> name[2]
  ’e’
    字符串中索引是从0开头的,获取字符串中第多少个地点的字符。

    7.__getnewargs__(self,*args,**kwargs)

    def __getnewargs__(self, *args, **kwargs): # real signature
unknown

    ”””__getnewargs__是跟参数有关的”””
    pass

    8.__hash__(self,*args,**kwargs)

    def __hash__(self, *args, **kwargs): # real signature
unknown
    ””” Return hash(self). “””
    pass   

    9.__iter__(self,*args,**kwargs)

    def __iter__(self, *args, **kwargs): # real signature
unknown
    ””” Implement iter(self). “””
    pass

    10.__len__(self,*args,**kwargs)

    def __len__(self, *args, **kwargs): # real signature
unknown
    ””” Return len(self). “””

        “””重返字符串的尺寸,等价与len(self)”””
    pass

    实举例下:

    >>> name = “Alexissb”
  >>> name.__len__()
  8
  >>> len(name)
  8
    11.count(self,sub,start=None,end=None)
    def count(self, sub, start=None, end=None): # real signature
unknown; restored from __doc__
    ”””
    S.count(sub[, start[, end]]) -> int

        重临在字符串中冒出钦定字符的个数,重返七个整数

    Return the number of non-overlapping occurrences of substring
sub in
    string S[start:end]. Optional arguments start and end are
    interpreted as in slice notation.
    ”””
    return 0

   
count(self,sub,start=None,end=None)是用来总结字符串中出现一定字符的个数,再次来到三个平头,实例如下:

    >>> name = “Alexssbbafadgcxlsdgpssl”
    >>> name.count(“a”)
  2
    >>> name.count(“D”)
  0
    总括字符串中冒出内定字符的个数,当不设不经常重临0。

    12.encode(self,encoding=’utf-8′,errors=’strict’)

    def encode(self, encoding=’utf-8′, errors=’strict’): # real
signature unknown; restored from __doc__
    ”””
    S.encode(encoding=’utf-8′, errors=’strict’) -> bytes
        编码
    Encode S using the codec registered for encoding. Default
encoding
    is ‘utf-8’. errors may be given to set a different error
    handling scheme. Default is ‘strict’ meaning that encoding
errors raise
    a UnicodeEncodeError. Other possible values are ‘ignore’,
‘replace’ and
    ’xmlcharrefreplace’ as well as any other name registered with
    codecs.register_error that can handle UnicodeEncodeErrors.
    ”””
    return b””

    实比如下:

    >>> name = “李杰”
  >>> name.encode(“gbk”)
  b’\xc0\xee\xbd\xdc’
    将字符串转化为”gbk”格式,机器度和胆识别的格式。

    13.endswith(self,suffix,start=None,end=None)

    def endswith(self, suffix, start=None, end=None): # real signature
unknown; restored from __doc__
    ”””
    S.endswith(suffix[, start[, end]]) -> bool
       
字符串是不是以钦点的字符截止,endswith(self,suffix,start=None,end=None)
    Return True if S ends with the specified suffix, False
otherwise.
    With optional start, test S beginning at that position.
    With optional end, stop comparing S at that position.
    suffix can also be a tuple of strings to try.
    ”””
    return False

   
endswith(self,suffix,start=None,end=None)判断字符串以有个别钦命的字符甘休,若是是,则赶回布尔值True;不然重返False。

    >>> name = “Alexsssbdfgedlmnopqqsstabsc”
  >>> name.endswith(“c”)
  True
  >>> name.endswith(“s”,0,5)
  True
    14.expandtabs(self,tabsize=8)

    def expandtabs(self, tabsize=8): # real signature unknown; restored
from __doc__
    ”””
    S.expandtabs(tabsize=8) -> str
       
将字符串中的tab键转化为空格,默许时8个职位的空格,能够协调设置参数
    Return a copy of S where all tab characters are expanded using
spaces.
    If tabsize is not given, a tab size of 8 characters is
assumed.
    ”””
    return “”

   
expandtabs(self,tabsize=8)将字符串中的tab(\t)将转向为空格,私下认可是转账为8个空格,能够协和安装转化为多少个空格。示举例下:

    >>> user = ”    Alex”
  >>> user.expandtabs()
  ’        Alex’
  >>> user.expandtabs(2)
  ’  Alex’
  >>> user.expandtabs(0)
  ’Alex’
  >>> user.expandtabs(tabsize=3)
  ’   Alex’
    15.find(self,sub,start=None,end=None)

    def find(self, sub, start=None, end=None): # real signature
unknown; restored from __doc__
    ”””
    S.find(sub[, start[, end]]) -> int
       
查找钦命字符在字符串中的地方,再次来到地点索引,借使找寻不到,则赶回-1(return
-1 on failure)
    Return the lowest index in S where substring sub is found,
    such that sub is contained within S[start:end]. Optional
    arguments start and end are interpreted as in slice notation.

    Return -1 on failure.
    ”””
    return 0
   
find(self,sub,start=None,end=None)查找钦定字符在字符串中的地方,假若寻觅不到,则赶回-1(即查找字符一纸空文钦赐字符串中),示举例下:

    >>> name
  ’Alexsssbdfgedlmnopqqsstabsc’
  >>> name.find(“s”)
  4
  >>> name.find(“s”,8,len(name)-1)
  20
  >>> name.find(“S”)
  -1
   
find(self,sub,start=None,end=None)查找这么些字符第一遍面世的地点索引。只查找第三个岗位索引,查找未果重临-1.
    16.index(self,sub,start=None,end=None)

    def index(self, sub, start=None, end=None): # real signature
unknown; restored from __doc__
    ”””
    S.index(sub[, start[, end]]) -> int
       
    Like S.find() but raise ValueError when the substring is not
found.
    ”””
    return 0

     
index(self,sub,start=None,end=None)跟find()一样是寻觅钦定字符在字符串中的地点索引,不相同的是,就算index()查找未果,则报错。找寻不到报错。 
示比方下:

     >>> name
  ’Alexsssbdfgedlmnopqqsstabsc’
  >>> name.index(“s”)
  4
  >>> name.index(“s”,8,len(name)-1)
  20
  >>> name.index(“S”)
  Traceback (most recent call last):
     File “<stdin>”, line 1, in <module>
  ValueError: substring not found    
上边能够看到,index()和find()是同样的,都以回来寻找字符的地方索引,不过当index()查找不到的时候会报错。

    17.format_map(self,mapping)

    def format_map(self, mapping): # real signature unknown; restored
from __doc__
    ”””
    S.format_map(mapping) -> str

    Return a formatted version of S, using substitutions from
mapping.
    The substitutions are identified by braces (‘{‘ and ‘}’).
    ”””
    return “”

    18.isalnum(self)

    def isalnum(self): # real signature unknown; restored from
__doc__
    ”””
    S.isalnum() -> bool
       决断字符串中全部的字符是或不是都以字符数字组合
    Return True if all characters in S are alphanumeric
    and there is at least one character in S, False otherwise.
    ”””
    return False
   
示举例下:判别字符串中是还是不是持有因素独有数字和字母组成,alnum是单词阿尔法numeric的缩写,字母数字
    >>> name.isalnum()
  True
  >>> nums = “2233”
  >>> nums.isalnum()
  True

    19.isalpha()

    def isalpha(self): # real signature unknown; restored from
__doc__
    ”””
    S.isalpha() -> bool
        判别字符串中颇具的因素是还是不是都以字母组成
    Return True if all characters in S are alphabetic
    and there is at least one character in S, False otherwise.
    ”””
    return False

   
推断字符串全数字符是或不是都以字母alpha是单词alphabetic(字母)的缩写:  

>>> nums = “2233”
  >>> name.isalpha()
  True
  >>> nums.isalpha()
  False
    20.isdecimal(self)

    def isdecimal(self): # real signature unknown; restored from
__doc__
    ”””
    S.isdecimal() -> bool
       
如若字符串中值包括十进制的数字,则赶回True;否则重返布尔值False.
    Return True if there are only decimal characters in S,
    False otherwise.
    ”””
    return False

   
isdecimal(self)判别字符串中是否只蕴含十进制的数字,借使是,则赶回True;不然重临False。示比方下:

    >>> s1 = “a122”
  >>> s2 = “222”
  >>> s3 = “&b#s”
  >>> s1.isdecimal()
  False
  >>> s2.isdecimal()
  True
  >>> s3.isdecimal()
  False
    21.isdigit(self)
    def isdigit(self): # real signature unknown; restored from
__doc__
    ”””
    S.isdigit() -> bool
        剖断字符串是否仅仅由数字组合
    Return True if all characters in S are digits
    and there is at least one character in S, False otherwise.
    ”””
    return False

   
isdigit(self)推断字符串中是还是不是仅仅包括数字,即由数字构成的字符串。实比方下:

    >>> s1 = “a122”
  >>> s2 = “222”
  >>> s3 = “&b#s”

    >>> s1.isdigit()
  False
  >>> s2.isdigit()
  True
  >>> s3.isdigit()
  False
    22.isidentifier(self)

    def isidentifier(self): # real signature unknown; restored from
__doc__
    ”””
    S.isidentifier() -> bool

    Return True if S is a valid identifier according
    to the language definition.

    Use keyword.iskeyword() to test for reserved identifiers
    such as “def” and “class”.
    ”””
    return False

    isidentifier(self),实举例下:

    >>> s2 = “Alex”
  >>> s3 = “list”
  >>> s2.isidentifier()
  True
  >>> s3.isidentifier()
  True
  >>> s4 = “55”
  >>> s4.isidentifier()
  False
  >>> s5 = “gengcx”
  >>> s5.isidentifier()
  True

    23.islower(self)

    def islower(self): # real signature unknown; restored from
__doc__
    ”””
    S.islower() -> bool
        决断是不是都以小写
    Return True if all cased characters in S are lowercase and
there is
    at least one cased character in S, False otherwise.
    ”””
    return False

    islower(self)决断字符串是还是不是都以小写,

    >>> s1 = “Alex”
  >>> s2 = “23abc”
  >>> s3 = “alex”
  >>> s4 = “AlexSb&&”
  >>> s5 = “a%@”
  >>> s1.islower()
  False
  >>> s2.islower()
  True
  >>> s3.islower()
  True
  >>> s4.islower()
  False
  >>> s5.islower()
  True
    24.isnumeric(self)

    def isnumeric(self): # real signature unknown; restored from
__doc__
    ”””
    S.isnumeric() -> bool

    Return True if there are only numeric characters in S,
    False otherwise.
    ”””
    return False

   
isnumeric(self)判定字符串S中是还是不是值富含数字在内部,假若是,再次回到True;否则再次回到False.

    >>> name = “Alex222”
  >>> nums = “234239”
  >>> num = “23se”
  >>> l1 = “2.35”
  >>> name.isnumeric()
  False
  >>> nums.isnumeric()
  True
  >>> num.isnumeric()
  False
  >>> l1.isnumeric()
  False
    25.isprintable(self)

    def isprintable(self): # real signature unknown; restored from
__doc__
    ”””
    S.isprintable() -> bool
      
剖断一个字符串是不是里面包车型大巴字符皆以能够打字与印刷出来的要么字符串是空的,借使是回到True;不然再次来到False
    Return True if all characters in S are considered
    printable in repr() or S is empty, False otherwise.
    ”””
    return False

    isprintable(self) 

    >>> name = ”    Alex”
  >>> name.isprintable()
  False
  >>> user = “Alex”
  >>> user.isprintable()
  True

    >>> s1 = “”
    >>> s1.isprintable()
  True
    isprintable(s1)中s1是空的字符串,不过也回到True.
    26.isspace(self)

    def isspace(self): # real signature unknown; restored from
__doc__
    ”””
    S.isspace() -> bool
        推断字符串中是还是不是都是室如悬磬
    Return True if all characters in S are whitespace
    and there is at least one character in S, False otherwise.
    ”””
    return False

   
isspace(self)判定字符串中是否都是赤贫如洗,倘使是回来True;不然重返False。示比方下:

    >>> s1 = ”    “
  >>> s2 = ”       “
  >>> s3 = “cs   “
  >>> s1.isspace()
  True
  >>> s2.isspace()
  True
  >>> s3.isspace()
  False
    27.istitle(self)

    def istitle(self): # real signature unknown; restored from
__doc__
    ”””
    S.istitle() -> bool
        推断字符串中负有字符是或不是是首字母大写方式,倘使是回来True
    Return True if S is a titlecased string and there is at least
one
    character in S, i.e. upper- and titlecase characters may only
    follow uncased characters and lowercase characters only cased
ones.
    Return False otherwise.
    ”””
    return False

   
istitle(self)判定是或不是首字母大写,纵然是回来True;不然重返False。实比如下:

    >>> s1 = “Alex is sb”
  >>> s2 = “Alex Is Sb”
  >>> s3 = “alex is sb”
  >>> s1.istitle()
  False
  >>> s2.istitle()
  True
  >>> s3.istitle()
  False
    28.isupper(self)

    def isupper(self): # real signature unknown; restored from
__doc__
    ”””
    S.isupper() -> bool
        判定全数字母是不是都是大写
    Return True if all cased characters in S are uppercase and
there is
    at least one cased character in S, False otherwise.
    ”””
    return False
      isupper(self)判别字符串中保有字符是或不是都是大写情势:实举例下:

    >>> s1 = “Alex is sb”
  >>> s2 = “Alex Is Sb”
    >>> s3 = “alex is sb”

    >>> s4 = “ALEX IS SB”
    >>> s1.isupper()
  False
  >>> s2.isupper()
  False
  >>> s3.isupper()
  False

    >>> s4.isupper()
  True

    29.join(self,iterable)

    def join(self, iterable): # real signature unknown; restored from
__doc__
    ”””
    S.join(iterable) -> str
        字符串的拼凑,把字符串拼接到一同
    Return a string which is the concatenation of the strings in
the
    iterable. The separator between elements is S.
    ”””
    return “”
   
join(self,iterable)拼接,字符串和列表直接的拼凑,有例外格局的拼接,上边来商讨一下:

    >>> sign = “-“
  >>> name = “alex”
  >>> li = [“a”,”l”,”e”,”x”,”s”,”b”]
  >>> l1 = “”
   
1.字符串和字符串进行拼接,将拼接中的字符串的每贰个要素与字符串中的成分举办拼接,即iterable+self+iterable+self… 

  >>sign.join(name)
  ’a-l-e-x’
  >>> name.join(“sb”)
  ’salexb’
  >>> name.join(“issb”)
  ’ialexsalexsalexb’
  2.字符串和列表实行拼接,列表中的每贰个成分都与字符串的因素实行拼接:

  >>> sign.join(li)
  ’a-l-e-x-s-b’
  >>> l1.join(li)
  ’alexsb’

   
其实在Python中,字符串存款和储蓄的格式就是列表存款和储蓄的,比如”alexsb”存款和储蓄就是[“a”,”l”,”e”,”x”,”s”,”b”],因此字符串与列表拼接与字符串与字符串拼接是一致的。

    30.ljust(self,width,fillchar=None)

    def ljust(self, width, fillchar=None): # real signature unknown;
restored from __doc__
    ”””
    S.ljust(width[, fillchar]) -> str
       固定长度,字符串侧边拼接内定的字符
    Return S left-justified in a Unicode string of length width.
Padding is
    done using the specified fill character (default is a space).
    ”””
    return “”
    ljust(self,width,fillchar=None),固定长度,self+fillchar,实举个例子下:

    >>> name = “alexsb”
    >>> name.ljust(12,”-“)
  ’alexsb——‘

    31.rjust(self,width,fillchar=None)

    def rjust(self, width, fillchar=None): # real signature unknown;
restored from __doc__
    ”””
    S.rjust(width[, fillchar]) -> str

    Return S right-justified in a string of length width. Padding
is
    done using the specified fill character (default is a space).
    ”””
    return “”
    固定字符串长度,在字符串右边链接钦赐字符,实举个例子下:

    >>> name = “alexsb”   

  >>> name.rjust(12,”-“)
  ’——alexsb’

    32.lower(self)

    def lower(self): # real signature unknown; restored from
__doc__
    ”””
    S.lower() -> str
        将字符串全体中间转播为小写情势
    Return a copy of the string S converted to lowercase.
    ”””
    return “”
    33.lstrip(self,chars=None)

    def lstrip(self, chars=None): # real signature unknown; restored
from __doc__
    ”””
    S.lstrip([chars]) -> str

    Return a copy of the string S with leading whitespace
removed.
    If chars is given and not None, remove characters in chars
instead.
    ”””
    return “”
   
lstrip(self,chars=None)是去除字符串左侧的空格,暗许是删除空格,其实能够钦命删除任何字符,实举例下:

    >>> name = ”   AlexAesbb   “
  >>> name.lstrip()
  ’AlexAesbb   ‘

    34.rstrip(self,chars=None)

    def rstrip(self, chars=None): # real signature unknown; restored
from __doc__
    ”””
    S.rstrip([chars]) -> str
        删除字符串右边的空格
    Return a copy of the string S with trailing whitespace
removed.
    If chars is given and not None, remove characters in chars
instead.
    ”””
    return “”
    rstrip(self,chars=None)删除字符串侧面的空格,实比方下:

    >>> name = ”   AlexAesbb   ”   

    >>> name.rstrip()
‘   AlexAesbb’

    35.strip(self,chars=None)

    def strip(self, chars=None): # real signature unknown; restored
from __doc__
    ”””
    S.strip([chars]) -> str

    Return a copy of the string S with leading and trailing
    whitespace removed.
    If chars is given and not None, remove characters in chars
instead.
    ”””
    return “”
     strip(self,chars=None)删除字符串两边的空格,示比如下:

    >>> name = ”   AlexAesbb   ”   

    >>> name.strip()
  ’AlexAesbb’

    36.maketrans(self,*args,**kwargs)

    def maketrans(self, *args, **kwargs): # real signature unknown
    ”””
    Return a translation table usable for str.translate().

    If there is only one argument, it must be a dictionary mapping
Unicode
    ordinals (integers) or characters to Unicode ordinals, strings
or None.
    Character keys will be then converted to ordinals.
    If there are two arguments, they must be strings of equal
length, and
    in the resulting dictionary, each character in x will be mapped
to the
    character at the same position in y. If there is a third
argument, it
    must be a string, whose characters will be mapped to None in
the result.
    ”””
    pass
    37.translate(self,table)

    def translate(self, table): # real signature unknown; restored from
__doc__
    ””
    S.translate(table) -> str

    Return a copy of the string S in which each character has been
mapped
    through the given translation table. The table must implement
    lookup/indexing via __getitem__, for instance a dictionary
or list,
    mapping Unicode ordinals to Unicode ordinals, strings, or None.
If
    this operation raises LookupError, the character is left
untouched.
    Characters mapped to None are deleted.
    ”””
    return “”
    示举个例子下:

    >>> intab = “aeiou”
  >>> outtab = “12345”

    >>> trantab = intab.maketrans(intab,outtab)
  >>> trantab
  {97: 49, 111: 52, 117: 53, 101: 50, 105: 51}

    >>> str = “This is string example …. wow!!!”
    >>> str.translate(trantab)
  ’Th3s 3s str3ng 2x1mpl2 …. w4w!!!’

   
上边代码含义是,把intab中种种成分与outtab中种种成分一一对应,然后translate()替换当中对应的要素。

    38.partition(self,sep)

    def partition(self, sep): # real signature unknown; restored from
__doc__
    ”””
    S.partition(sep) -> (head, sep, tail)
        字符串分隔,以sep分隔为前中后三有些
    Search for the separator sep in S, and return the part before
it,
    the separator itself, and the part after it. If the separator
is not
    found, return S and two empty strings.
    ”””
    pass
   
partition(self,sep)字符串分隔,以字符串sep分隔为前中后三部分,何况以找到的率先个字符为分隔:

    >>> name = ‘   AlexAesbb   ‘
  >>> name.partition(“x”)
  (‘   Ale’, ‘x’, ‘Aesbb   ‘)
  >>> name.partition(“A”)
  (‘   ‘, ‘A’, ‘lexAesbb   ‘)

    39.replace(self,old,new,count=None)

    def replace(self, old, new, count=None): # real signature unknown;
restored from __doc__
    ”””
    S.replace(old, new[, count]) -> str
        字符串的研究替换
    Return a copy of S with all occurrences of substring
    old replaced by new. If the optional argument count is
    given, only the first count occurrences are replaced.
    ”””
    return “”
   
字符串的更迭,old哪个字符要替换,new替换到什么,count替换多少个,实比如下:

    >>> name = ‘   AlexAesbb   ‘
  >>> name.replace(“A”,”M”)
  ’   MlexMesbb   ‘
  >>> name.replace(“A”,”M”,1)
  ’   MlexAesbb   ‘

    字符串的追寻替换,暗中认可替换全体,能够钦点替换的个数。

    39.rfind(self,sub,start=None,end=None)

    def rfind(self, sub, start=None, end=None): # real signature
unknown; restored from __doc__
    ”””
    S.rfind(sub[, start[, end]]) -> int
        从侧边开端查找
    Return the highest index in S where substring sub is found,
    such that sub is contained within S[start:end]. Optional
    arguments start and end are interpreted as in slice notation.

    Return -1 on failure.
    ”””
    return 0
    从字符串左边初阶查找,查找钦点字符在字符串中的地方索引:实举个例子下:

    >>> name = ‘   AlexAesbb   ‘
  >>> name.rfind(“A”)
  7
  >>> name.find(“A”)
  3
  >>> name.rfind(” “)
  14

    从侧面查找内定字符在字符串中的地点索引,假诺寻觅不到再次回到-1.

    40.rindex(self,sub,start=None,end=None)

    def rindex(self, sub, start=None, end=None): # real signature
unknown; restored from __doc__
    ”””
    S.rindex(sub[, start[, end]]) -> int

    Like S.rfind() but raise ValueError when the substring is not
found.
    ”””
    return 0
   
rindex(self,sub,start=None,end=None)从字符串左边查找内定字符的岗位索引,纵然寻觅不到就能报错。

    41.rpartition(self,sep)

    def rpartition(self, sep): # real signature unknown; restored from
__doc__
    ”””
    S.rpartition(sep) -> (head, sep, tail)
        从字符串左边开始查找分隔
    Search for the separator sep in S, starting at the end of S,
and return
    the part before it, the separator itself, and the part after
it. If the
    separator is not found, return two empty strings and S.
    ”””
    pass
   
rpartition(self,sep)从字符串左侧初始查找分隔,与partition(self,sep)正好相反,示比如下,分隔字符串获得三个元组:

    >>> name = ‘   AlexAesbb   ‘
  >>> name.partition(“A”)
  (‘   ‘, ‘A’, ‘lexAesbb   ‘)
  >>> name.rpartition(“A”)
  (‘   Alex’, ‘A’, ‘esbb   ‘)

    42.rsplit(self,sep=None,maxsplit=-1)

    def rsplit(self, sep=None, maxsplit=-1): # real signature unknown;
restored from __doc__
    ”””
    S.rsplit(sep=None, maxsplit=-1) -> list of strings

    Return a list of the words in S, using sep as the
    delimiter string, starting at the end of the string and
    working to the front. If maxsplit is given, at most maxsplit
    splits are done. If sep is not specified, any whitespace
string
    is a separator.
    ”””
    return []
   
rsplit(self,sep=None,maxsplit=-1)分隔字符串,并转移三个存放的列表,实举个例子下:

    >>> name = “Alexsbegcex”
  >>> name.split(“e”)
  [‘Al’, ‘xsb’, ‘gc’, ‘x’]
  >>> name.rsplit(“e”)
  [‘Al’, ‘xsb’, ‘gc’, ‘x’]

    >>> name.split(“e”,0)
  [‘Alexsbegcex’]
  >>> name.split(“e”,1)
  [‘Al’, ‘xsbegcex’]
  >>> name.split(“e”,2)
  [‘Al’, ‘xsb’, ‘gcex’]
  >>> name.split(“e”,3)
  [‘Al’, ‘xsb’, ‘gc’, ‘x’]
  >>> name.split(“e”,4)
  [‘Al’, ‘xsb’, ‘gc’, ‘x’]
  >>> name.split(“e”,-1)
  [‘Al’, ‘xsb’, ‘gc’, ‘x’]

   
以钦点字符串分隔,并且替换钦命字符,分隔产生多个列表,能够内定分隔字符的个数。

    43.split(self,sep=None,maxsplit=-1)

    def split(self, sep=None, maxsplit=-1): # real signature unknown;
restored from __doc__
    ”””
    S.split(sep=None, maxsplit=-1) -> list of strings
        分隔字符串,生成二个列表,能够钦命分隔的次数,默许是全部相间
    Return a list of the words in S, using sep as the
    delimiter string. If maxsplit is given, at most maxsplit
    splits are done. If sep is not specified or is None, any
    whitespace string is a separator and empty strings are
    removed from the result.
    ”””
    return []
    44.splitlines(self,keepends=None)

    def splitlines(self, keepends=None): # real signature unknown;
restored from __doc__
    ”””
    S.splitlines([keepends]) -> list of strings

    Return a list of the lines in S, breaking at line boundaries.
    Line breaks are not included in the resulting list unless
keepends
    is given and true.
    ”””
    return []
   
splitlines(self,keepends=None)以”\n”换行符的款型分隔字符串,实比如下:

    >>> user = “””
  … alex
  … aoi
  … marry”””

    >>> user.splitlines()
  [”, ‘alex’, ‘aoi’, ‘marry’]

    45.startswith(self,prefix,start=None,end=None)

    def startswith(self, prefix, start=None, end=None): # real
signature unknown; restored from __doc__
    ”””
    S.startswith(prefix[, start[, end]]) -> bool
        字符串是不是以钦定字符开端,能够钦命起首地点
    Return True if S starts with the specified prefix, False
otherwise.
    With optional start, test S beginning at that position.
    With optional end, stop comparing S at that position.
    prefix can also be a tuple of strings to try.
    ”””
    return False
   
startswith(self,prefix,start=None,end=None)判别字符串是不是以钦命字符开始,可以钦点初步地点,与endswith(self,prefix,start=None,end)

刚巧相反,示举例下:

    >>> name = ‘Alexsbegcex’
    >>> name.startswith(“A”)
  True
    >>> name.startswith(“w”)
  False

    >>> name.startswith(“e”,2,5)
  True

    46.swapcase(self)

    def swapcase(self): # real signature unknown; restored from
__doc__
    ”””
    S.swapcase() -> str
        将一个字符串中享有大写字符转变为小写,小写转换为题写
    Return a copy of S with uppercase characters converted to
lowercase
    and vice versa.
    ”””
    return “”
   
swapcase(self)将多个字符串中有着字符小写转化为大写,大写转化为小写,好贱呀那几个办法,实举个例子下:

    >>> name = ‘Alexsbegcex’
  >>> name.swapcase()
  ’aLEXSBEGCEX’

    47.title(self)

    def title(self): # real signature unknown; restored from
__doc__
    ”””
    S.title() -> str
        将字符串首字母调换为题写
    Return a titlecased version of S, i.e. words start with title
case
    characters, all remaining cased characters have lower case.
    ”””
    return “”
    48.upper(self)

    def upper(self): # real signature unknown; restored from
__doc__
    ”””
    S.upper() -> str
        将字符串全体字母都改造为题写
    Return a copy of S converted to uppercase.
    ”””
    return “”
    49.zfill(self,width)

    def zfill(self, width): # real signature unknown; restored from
__doc__
    ”””
    S.zfill(width) -> str
        钦定宽度,不足右边补零
    Pad a numeric string S with zeros on the left, to fill a
field
    of the specified width. The string S is never truncated.
    ”””
    return “”
    zfill(self,width)钦点宽度,不足右侧补0,否则不改变。实举例下:

    >>> name = ‘Alexsbegcex’
  >>> name.zfill(20)
  ’000000000Alexsbegcex’
  >>> name.zfill(5)
  ’Alexsbegcex’
    50.__contains__(self,*args,**kwargs)

    def __contains__(self, *args, **kwargs): # real signature
unknown
    ””” Return key in self. “””

        推断字符串中是或不是包括钦点字符
    pass
   
__contains__(self,*args,**kwargs)判定字符串中是或不是满含钦点字符,实举个例子下:

    >>> name = ‘Alexsbegcex’
  >>> name.__contains__(“e”)
  True
  >>> name.__contains__(“E”)
  False

   
 

 

字符串是编程中常用的类型,字符型在内部存款和储蓄器中是以单个情势累积的,举例name =
“alex”,在内部存款和储蓄器中存放的花样为…

打字与印刷结果:

 结果

1 result1:Love python
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__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', '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']
  ak am il.l    iu
#######  aK am  il.L    iu########
2
True
  aK am il.L    iu
  aK am  il.L  iu
8
-1
8
False
1#2#3#4#5#6#7
  aK am il.L    iu$$$$$$$$$$$$$$$
  ak am il.l    iu
aK am   il.L    iu
('  aK a', 'm', '\til.L\tiu')
  aK qqqqqq il.L    iu
['aK', 'am', 'il.L', 'iu']
['  aK am\til.L\tiu']

 

 图片 1

  •  casefold(self) 官方解释比较霸道,确实是相比较霸道,全数的假名都成为小写,然而好像用的十分少

    1 # casefold(self)
    2 name = ‘HELLo Python My Name IS RookieJX’
    3 result2 = name.casefold()
    4 print(‘result2:%s’%result2)

  打字与印刷结果:

1 result2:hello python my name is rookiejx

 

  •  center(self, width,
    fillchar=None) 那几个是将原字符串居中,如果self长度小于width,那么余下的一些就用
    fillchar
    字符填充并,默认为空格,假若多余的是奇数,那么最后剩余的三个就填充到右边。当中fillchar只好为单个字符。

    1 # center(self, width, fillchar=None)
    2 name = ‘Python’
    3 result3 = name.center(9,”H”)
    4 print(‘result3:%s’%result3)

  打字与印刷结果:

1 result3:HHPythonH

 

  •  count(self, sub, start=None,
    end=None) 查询某些字符或许字符串在self中出现的次数,暗中认可是在整整self上询问,也能够自定义地点

    1 # count(self, sub, start=None, end=None)
    2 name = ‘Hello Python’
    3 result4 = name.count(“lo”,0,40)
    4 print(‘result4:%s’%result4)

  打印结果:

1 result4:1

 

  • encode(self, encoding=’utf-8′, errors=’strict’) 编码为utf-8格式编码,假如出错使用严峻,别的还应该有’ignore’,
    ‘replace’ 等

    1 # encode(self, encoding=’utf-8′, errors=’strict’)
    2 name = ‘Hello Python’
    3 result5 = name.encode(‘utf-8′,’strict’)
    4 print(‘result5:%s’%result5)

  打字与印刷结果:

1 result5:b'Hello Python'

 

  •  endswith(self, suffix, start=None,
    end=None) 以什么样为了却,默许是全体字符串,能够团结挑选尺寸

    1 # endswith(self, suffix, start=None, end=None)
    2 name = ‘Hello Python’
    3 result6 = name.endswith(‘o’,0,3)
    4 print(‘result6:%s’%result6)

  打字与印刷结果:

1 result6:False

 

  •  expandtabs(self,
    tabsize=8) 将字符串中负有的tab键转变来空格键,默以为8

    1 # expandtabs(self, tabsize=8)
    2 result7 = ‘hate\tPython’
    3 print(‘origin result7:%s’%result7)
    4 result8 = result7.expandtabs() #将字符串中颇具的tab键调换来空格键,暗许为8
    5 print(‘result8:%s’%result8)
    6 result9 = result7.expandtabs(20) #改动暗中同意值
    7 print(‘result9:%s’%result9)

  打字与印刷结果:

1 origin result7:hate    Python
2 result8:hate    Python
3 result9:hate                Python

 

  •  find(self, sub, start=None,
    end=None) 查找有些字符或许字符串在字符串中的下标,默以为寻觅全体字符串

    1 # find(self, sub, start=None, end=None)
    2 name = ‘Hello Python’
    3 result10 = name.find(‘P’) #查找有些字符可能字符串在字符串中的下标,默感觉寻觅全体字符串
    4 print(‘result10:%s’%result10)
    5 result11 = name.find(‘P’,0,4) #能够自定义查找范围,若无就赶回 -1
    6 print(‘result11:%s’%result11)

  打字与印刷结果:

1 result10:6
2 result11:-1

 

  •  format(*args,
    **kwargs) 好像很暴力的指南,格式化字符串,有广大用法

    1 # format(*args, **kwargs)
    2 # 好像很暴力的金科玉律,格式化字符串,有相当的多用法
    3 # 1.方可选用 {} 用作占位符 这里分割的时候需求动用 . 不是用 , 那一点须求留意 4 print(‘I am {},I {} ‘.format(‘rookieJX’,’Love Python’))
    5 # 2.也能够选取 {0} {1}等体制的占位符
    6 print(‘I am {1},I {0}’.format(‘Love Python’,’rookieJX’))
    7 # 3.还足以应用变量格局的占位符
    8 print(‘My job is {job}’.format(job = ‘IT’))
    9 # 4.还足以勾兑使用
    10 print(‘I am {1},My job is {job}’.format(‘haha’,’rookieJX’,job = ‘IT’))

  打字与印刷结果:

1 I am rookieJX,I Love Python 
2 I am rookieJX,I Love Python
3 My job is IT
4 I am rookieJX,My job is IT

 

  •  format_map(self,
    mapping) 暂且了然的还非常少

 

  •  index(self, sub, start=None,
    end=None) 类似于find方法,可是当要探求的字符串不在查找的字符串中的话会报错

    1 # index(self, sub, start=None, end=None)
    2 name = ‘Hello Python’
    3 result12 = name.index(‘P’) # 类似于find方法,可是当要物色的字符串不在查找的字符串中的话会报错
    4 print(‘result12:%s’%result12)
    5 result13 = name.index(‘P’,0,10) # 还能够自定义限制查找的范围
    6 print(‘result13:%s’%result13)

  打字与印刷结果:

1 result12:6
2 result13:6

 

  •  isalnum(self) 字符串中至少有一个字符,並且具有的字符都以字母恐怕数字再次来到为True
    不然重临为 False (空格也回到False)

    1 # isalnum(self)
    2 name = ‘Hello Python’
    3 result14 = name.isalnum() # 字符串中最少有贰个字符,况且有所的字符都是字母或然数字重返为True 否则重回为 False (空格也回到False)
    4 print(‘result14:%s’%result14)

  打字与印刷结果:

1 result14:False

 

  •  is阿尔法(self) 字符串中至少有三个是字符,而且具备的字符都是字母重回为
    True 不然再次来到为 False (空格也回到False)

    1 # is阿尔法(self)
    2 name = ‘Hello Python’
    3 result15 = name.is阿尔法()
    4 print(‘result15:%s’%result15) # 字符串中最少有一个是字符,况且有着的字符都以字母重临为 True 不然再次回到为 False (空格也回到False)

  打字与印刷结果:

1 result15:False

 

  •  isdecimal(self) 推断字符串是不是是十进制整数,尽管不是回来为
    False ,借使不是字符串就能报错

    1 # isdecimal(self)
    2 namedeclimal = “324.2” # 判定字符串是或不是是十进制整数,借使不是回去为 False ,假诺不是字符串就能够报错
    3 result16 = namedeclimal.isdecimal()
    4 print(‘result16:%s’%result16)

  打字与印刷结果:

1 result16:False
  •  isdigit(self) 决断字符串中是否只含有数字

    1 # isdigit(self)
    2 namedeclimal = “324.2”
    3 result17 = namedeclimal.isdigit() # 剖断字符串中是还是不是只含有数字
    4 print(‘result17:%s’%result17)

  打字与印刷结果:

1 result17:False

 

  •  isidentifier(self) 推断字符串是不是是关键字

    1 # isidentifier(self)
    2 result18 = ‘str’.isidentifier() # 决断字符串是不是是关键字
    3 print(‘result18:%s’%result18)

  打印结果:

1 result18:True

 

  •  islower(self) 字符串中足足有贰个字符,字符全体为小写就再次回到True

    1 # islower(self)
    2 name = ‘Hello Python’
    3 result19 = name.islower() # 字符串中最少有三个字符,字符全体为小写就重临 True
    4 print(‘result19:%s’%result19)

  打字与印刷结果:

1 result19:False

 

  •  isnumeric(self) 字符串中若是全都以数字字符重临True 貌似跟 isdecimal 大概,一时半刻还平素不意识有哪些不一样的用法

    1 # isnumeric(self)
    2 result20 = ‘4232’.isnumeric() # 字符串中一经全都是数字字符重回 True 貌似跟 isdecimal 差相当少,近来还尚无开掘有啥样两样的用法
    3 print(‘result20:%s’%result20)

  打字与印刷结果:

1 result20:True

 

  •  isprintable(self) 判别字符串中兼有字符是还是不是是可知状态

    1 # isprintable(self)
    2 result21 = ‘I\aPython’.isprintable() # 判定字符串中全体字符是还是不是是可知状态
    3 print(‘result20:%s’%result21)

  打字与印刷结果:

1 result20:False

 

  •  isspace(self) 字符串中要是只至少有贰个字符,而且全体为空格时
    重临为True

    1 # isspace(self)
    2 result22 = ‘ ‘.isspace() # 字符串中倘诺只至少有四个字符,而且全体为空格时 重回为True
    3 print(‘result22:%s’%result22)

  打字与印刷结果:

1 result22:True

 

  •  istitle(self) 字符串是还是不是为标题格式
    正是每一个单词首字母都以大写

    1 # istitle(self)
    2 result23 = ‘This Is Python’.istitle() # 字符串是还是不是为标题格式 便是种种单词首字母都是大写
    3 print(‘result23:%s’%result23)

  打字与印刷结果:

1 result23:True

 

  •  isupper(self) 字符串至少有一个字符
    判别字符是还是不是是大写 要是是大写就回来 True
    (只会判断个中的阿尔巴尼亚语字符,特殊符号,数字不会咬定)

    1 # isupper(self)
    2 result24 = ‘NAME.803’.isupper() # 字符串至少有二个字符 剖断字符是不是是大写 假设是大写就赶回 True (只会判定个中的英文字符,特殊符号,数字不会判断)
    3 print(‘result24:%s’%result24)

  打字与印刷结果:

1 result24:True

 

  •  join(self,
    iterable) 将self字符串用iterable克制,每种多少个字符串之间插入
    iterable 字符串

    1 # join(self, iterable)
    2 name = ‘Hello Python’
    3 result25 = name.join(‘Hello World’) # 将iterable字符串打垮,各类七个字符串之间插入 string 字符串
    4 print(‘result25:%s’%result25)

  打字与印刷结果:

1 result25:HHello PythoneHello PythonlHello PythonlHello PythonoHello Python Hello PythonWHello PythonoHello PythonrHello PythonlHello Pythond

 

  •  ljust(self, width,
    fillchar=None) 原字符串左对齐,总字符串长度为自定义长度,左边填充字符
    默感到空格 假使定义长度小于元字符串长度,则不会开展操作

    1 # ljust(self, width, fillchar=None)
    2 name = ‘Hello Python’
    3 result26 = name.ljust(23,’H’) # 原字符串左对齐,总字符串长度为自定义长度,侧面填充字符 默以为空格 要是定义长度小于元字符串长度,则不会开展操作
    4 print(‘result26:%s’%result26)

  打字与印刷结果:

1 result26:Hello PythonHHHHHHHHHHH

 

  •  lower(self) 拷贝一份原有的字符串,并将之成为小写
    貌似跟casefold效果同样的

    1 # lower(self)
    2 name = ‘Hello Python’
    3 result27 = name.lower() # 拷贝一份原有的字符串,并将之成为小写 貌似跟casefold效果同样的
    4 print(‘result27:%s’%result27)

  打字与印刷结果:

1 result27:hello python

 

  •  lstrip(self,
    chars=None) 暗中认可截掉字符串左侧的空格,假如自定义字符,那么字符必需是从字符串的起来技艺截取成功

    1 # lstrip(self, chars=None)
    2 result28 = ‘ Hello’.lstrip() # 暗许截掉字符串左边的空格,假诺自定义字符,那么字符必得是从字符串的发端手艺截取成功
    3 print(‘result28:%s’%result28)
    4
    5 result29 = ‘Hello’.lstrip(‘H’) # 私下认可截掉字符串侧边包车型客车空格,即使自定义字符,那么字符必得是从字符串的开首技术截取成功
    6 print(‘result29:%s’%result29)

  打印结果:

1 result28:Hello
2 result29:ello

 

  •  maketrans(self, *args,
    **kwargs) 营造替换映射表,首先构建映射对应表格,映射前为intab,映射后为outtab.然后构建对应表格maketrans,最后伊始调换

    1 # maketrans(self, *args, **kwargs)
    2 intab = “aeiou”
    3 outtab = “12398”
    4 intro = “hello python in my heart”
    5 result29 = str.maketrans(intab,outtab)
    6 result30 = intro.translate(result29) # 营造替换映射表,首先创设映射对应表格,映射前为intab,映射后为outtab.然后营造对应表格maketrans,最终最初调换7 print(‘intro:%s’%result30)

  打字与印刷结果:

1 intro:h2ll9 pyth9n 3n my h21rt

 

  •  partition(self,
    sep) 依据钦赐字符串来划分原字符串,要是原字符串存在钦点字符串,结果为
    分割左侧原字符串,钦命字符串,分割后右字符串…借使不设有钦赐字符串则赶回原字符串,只会分开出现的首先个岗位

    1 # partition(self, sep)
    2 test = ‘Hello Python , Hello Python ,Hello World’
    3 result31 = test.partition(‘P’) # 依据内定字符串来划分原字符串,假如原字符串存在钦点字符串,结果为 分割侧边原字符串,钦命字符串,分割后右字符串…如若空中楼阁钦定字符串则赶回原字符串,只会分开出现的第七个位置4 print(‘result31:’,result31)

  打字与印刷结果:

1 result31: ('Hello ', 'P', 'ython , Hello Python ,Hello World')

 

  •  replace(self, old, new,
    count=None) 替换字符串.最大不超过多少次

    1 # replace(self, old, new, count=None)
    2 result32 = ‘love python love python love python love python love python ‘.replace(‘love’,’hate’,3) # 替换字符串.最大不超越多少次
    3 print(‘result32:%s’%result32)

  打字与印刷结果:

1 result32:hate python hate python hate python love python love python 

 

  •  rfind(self, sub, start=None,
    end=None) 查找钦赐字符串在原字符串中最侧边的职位,默感觉全部字符串

    1 # rfind(self, sub, start=None, end=None)
    2 result33 = ‘love python love ‘.rfind(‘lo’) # 查找钦命字符串在原字符串中最左边的岗位,默感觉全方位字符串
    3 print(‘result33:%s’%result33)

  打字与印刷结果:

1 result33:12

 

  •  rindex(self, sub, start=None,
    end=None) 查找钦定字符串在原字符串中最左边的岗位,默以为全方位字符串,跟rfind效果大约,然则只要找不到就能够报错

    1 # rindex(self, sub, start=None, end=None)
    2 result34 = ‘love python love ‘.rindex(‘lo’) # 查找内定字符串在原字符串中最侧边的岗位,默以为全方位字符串,跟rfind效果大概,但是假设找不到就能报错
    3 print(‘result34:%s’%result34)

  打字与印刷结果:

1 result34:12

 

  •  rjust(self, width,
    fillchar=None) 重返四个入手对其的原字符串,暗中认可用空格对其,能够自定义字符,可是倘固然自定义字符串的话,那么自定义的字符串必得能被剩下的空格整除,不然就能报错

    1 # rjust(self, width, fillchar=None)
    2 name = “love PyThon”
    3 result35 = name.rjust(50,’O’) # 重回多个左边对其的原字符串,暗许用空格对其,能够自定义字符,可是即使是自定义字符串的话,那么自定义的字符串必得能被剩下的空格整除,不然就能报错
    4 print(‘result35:%s’%result35)

  打字与印刷结果:

1 result35:OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOlove PyThon

 

  •  rpartition(self,
    sep) 类似于partition 只不过是从右侧起初查找

    1 # rpartition(self, sep)
    2 test2 = ‘Hello Python ,Hello Python , Hello WoPrld’
    3 result36 = test2.rpartition(‘P’) # 类似于partition 只可是是从侧面起初查找
    4 print(‘result36:’,result36)

  打字与印刷结果:

1 result36: ('Hello Python ,Hello Python , Hello Wo', 'P', 'rld')

 

  •  split(self, sep=None,
    maxsplit=-1) 根据钦命字符串来分割字符串,如若钦定最大分割字符串,那么久分割钦赐次数,假使不钦赐默感觉-1也便是最大

    1 # split(self, sep=None, maxsplit=-1)
    2 test3 = ‘Hello Python ,Hello Python , Hello WoPrld’
    3 result37 = test3.split(‘P’,2) # 依据内定字符串来分割字符串,如若内定最大分割字符串,那么久分割钦定次数,借使不钦点默感觉-1也正是最大
    4 print(‘result37:’,result37)

  打印结果:

1 result37: ['Hello ', 'ython ,Hello ', 'ython , Hello WoPrld']

 

  •  splitlines(self,
    keepends=None) 按照行(‘\r’, ‘\r\n’,
    \n’)分隔,再次回到八个含有各行作为成分的列表,假如参数 keepends 为
    False,不含有换行符,假诺为 True,则保留换行符.默以为False

    1 # splitlines(self, keepends=None)
    2 test4 = ‘Hello\r Pyth\non ,Hel\r\nlo Python , Hello WoPrld’
    3 result38 = test4.splitlines(True) # 按照行(‘\r’, ‘\r\n’, \n’)分隔,再次回到多少个满含各行作为成分的列表,若是参数 keepends 为 False,不包罗换行符,即使为 True,则保留换行符.默感到False
    4 print(‘result38:’,result38)

  打字与印刷结果:

1 result38: ['Hello\r', ' Pyth\n', 'on ,Hel\r\n', 'lo Python , Hello WoPrld']

 

  •  startswith(self, prefix, start=None,
    end=None) 查看是不是 以钦定字符串为起初 并可以钦点范围

    1 # startswith(self, prefix, start=None, end=None)
    2 test5 = ‘Hello\r Pyth\non ,Hel\r\nlo Python , Hello WoPrld’
    3 result39 = test5.startswith(‘ell’,0,30) # 查看是还是不是 以钦点字符串为初始 并得以钦点范围
    4 print(‘result39:’,result39)

  打字与印刷结果:

1 result39: False

 

  •  strip(self,
    chars=None) 对字符串执行去掉左右两侧的空格,默感到打消空格,可以安装为钦点字符

    1 # strip(self, chars=None)
    2 test6 = ‘H Hello Python ,Hello Python , Hello WoPrld H’
    3 result40 = test6.strip(‘H’) # 对字符串实行 去掉左右两侧的空格,默感到打消空格,能够安装为钦点字符
    4 print(‘result40:’,result40)

  打字与印刷结果:

1 result40:     Hello Python ,Hello Python , Hello WoPrld    

 

  •  swapcase(self) 翻转字符串中的大小写

    1 # swapcase(self)
    2 test7 = ‘H Hello Python ,Hello Python , Hello WoPrld H’
    3 result41 = test7.swapcase() # 翻转字符串中的大小写
    4 print(‘result41:’,result41)

  打字与印刷结果:

1 result41: h    hELLO pYTHON ,hELLO pYTHON , hELLO wOpRLD    h

 

  •  title(self) 将字符串中每一种单词首字母置为题写

    1 # title(self)
    2 test8 = ‘H hello python ,hello python , hello woPrld H’
    3 result42 = test8.title() # 将字符串中各样单词首字母置为大写
    4 print(‘result42:’,result42)

  打印结果:

1 result42: H    Hello Python ,Hello Python , Hello Woprld    H

 

  •  translate(self, table)  与maketrans(self, *args,
    **kwargs)同盟使用 

 

  •  upper(self) 将字符串改换为题写

    1 # upper(self)
    2 test9 = ‘H hello python ,hello python , hello woPrld H’
    3 result43 = test9.upper() # 将字符串改动为大写
    4 print(‘result43:’,result43)

  打字与印刷结果:

1 result43: H    HELLO PYTHON ,HELLO PYTHON , HELLO WOPRLD    H

 

  •   zfill(self,
    width) 左侧对齐,左侧填充数字0,长度为自定义

    1 # zfill(self, width)
    2 test10 = ‘H hello python ,hello python , hello woPrld H’
    3 result44 = test10.zfill(70) # 侧面对齐,侧面填充数字0,长度为自定义
    4 print(‘result44:’,result44)

  打字与印刷结果:

1 result44: 0000000000000000000H    hello python ,hello python , hello woPrld    H

 

  • 暂未符号

    myString = ‘Python’
    number = 1
    print(‘%s is best! is %d’%(myString,number))

  打字与印刷结果

Python is best! is 1

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图