首字母大写

temp = 'rttty'

ret = temp.capitalize()

print(ret)

===================================

内容居中

temp= 'kfkjdfj'

ret =temp.center(21,'*')   ###内容居中,两边空白处可以用任意符号填充

print(ret)

===================================

子序列个数

temp= ‘retegg  is hh’

ret = temp.count('g')  #计算字符串中的出现的个数

print(ret)

在指定范围内查找

a = ‘retegg  is hh’

ret = a.count('g',0,4)  #计算字符串中0到4的位置范围内g字母出现的次数

print(ret)

==================================

endwith 是否以........结尾

startwith是否以........开始

temp= ‘hello’

ret = temp.endwith('o')  ###判断是否以o 为结尾

print(ret)

---------------------------------------------------

temp = ‘hello’

ret = temp.endwith('e',0,2)  ###判断在0到2的范围内是否以e 为结尾

print(ret)

=================================================

expandtabs  将tab换成空格,一个tab转换成八个空格

temp =‘hello\t9999’  ###字符串中加上一个tab:\t

ret = temp.expandtabs()

print(ret)

================================================

find 查找,如果没有找到返回-1,从第0个位置开始找

temp = ‘start’

ret = temp.fnd('st')

print(ret)

=========================================

format 字符串格式化

temp = 'hello {0} ,gae {1}'  ###其中{0} {1} 为站位符

new = temp.format('Tom','55')

print(new)  ##运行后应该输出 hello Tom, gae 55

=============================================

index 获取子序列位置,如果没有找到就报错, 与find 类似

=============================================

isalnum   判断是否是字母和数字 ,isalpha 判断是否为字母,isdigit 判断是否为数字

temp = 'sfdgdfs999'

ret = temp.isalnum()

============================================

islower 检查所有内容是不是都是小写

isspace 判断是否是空格

istitle 判断是否是标题

isupper 检验全部是不是大写

============================================

join  连接

li =  ['ab','cd]

s = '_*'.join(li)

print(s) ## 应该输出ab_*cd

===========================================

ljust 内容左对齐,右侧填充,意思就是将原有字符向左移,右侧新增填充

rjust 将字符串右对齐左侧填充

temp = ‘ttt’

ret = temp.ljust(6,*)  ###定义总长度为6,剩余位置用*号填充,应该输出为ttt***

=============================================

lower  将字符串变小写

lstrip 移除字符串左侧空格

rstrip 移除字符串右侧空格

strip 移除字符串两侧空格

============================================

partition  分割字符串,成元组类型

s = ‘aa ff bb’

ret  = s.partition('ff')

print(ret) ##应该输出结果类型为元组 : (‘aa’ , ‘ff’ ,‘bb’)

===========================================

repalce 替换

s = ‘aa ff bb’

ret  = s.repalce ('ff',cc)

print(ret) ###将ff 替换成cc

==========================================

split 分割

s = ‘ttterrehh’

ret = s.split('e') # 通过e分割

print(ret)  ##应输出为:['ttt', 'rr', 'hhh']

=========================================

swapcase 大写变小写,小写变大写

s=‘sH’

ret = s.swapcase()

print(ret) ##输出Sh

============================================

title 变为标题

s =‘this is school’

ret = s.title() ##变为标题,首字母大写

============================================

索引

s = ‘tayy’

print(s[0])

print(s[1])

len(s)  获取字符长度

============================================

切片

获取前两个字符

print(s[0:2])  ##0=<0,1<2

============================================

for循环

s = ‘tayy’

for i in s:    ## i 为变量名,s为要循环的字符串等

  print(i)

class str(basestring):"""str(object='') -> stringReturn a nice string representation of the object.If the argument is a string, the return value is the same object."""def capitalize(self):  """ 首字母变大写 """"""S.capitalize() -> stringReturn a copy of the string S with only its first charactercapitalized."""return ""def center(self, width, fillchar=None):  """ 内容居中,width:总长度;fillchar:空白处填充内容,默认无 """"""S.center(width[, fillchar]) -> stringReturn S centered in a string of length width. Padding isdone using the specified fill character (default is a space)"""return ""def count(self, sub, start=None, end=None):  """ 子序列个数 """"""S.count(sub[, start[, end]]) -> intReturn the number of non-overlapping occurrences of substring sub instring S[start:end].  Optional arguments start and end are interpretedas in slice notation."""return 0def decode(self, encoding=None, errors=None):  """ 解码 """"""S.decode([encoding[,errors]]) -> objectDecodes S using the codec registered for encoding. encoding defaultsto the default encoding. errors may be given to set a different errorhandling scheme. Default is 'strict' meaning that encoding errors raisea UnicodeDecodeError. Other possible values are 'ignore' and 'replace'as well as any other name registered with codecs.register_error that isable to handle UnicodeDecodeErrors."""return object()def encode(self, encoding=None, errors=None):  """ 编码,针对unicode """"""S.encode([encoding[,errors]]) -> objectEncodes S using the codec registered for encoding. encoding defaultsto the default encoding. errors may be given to set a different errorhandling scheme. Default is 'strict' meaning that encoding errors raisea UnicodeEncodeError. Other possible values are 'ignore', 'replace' and'xmlcharrefreplace' as well as any other name registered withcodecs.register_error that is able to handle UnicodeEncodeErrors."""return object()def endswith(self, suffix, start=None, end=None):  """ 是否以 xxx 结束 """"""S.endswith(suffix[, start[, end]]) -> boolReturn 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 Falsedef expandtabs(self, tabsize=None):  """ 将tab转换成空格,默认一个tab转换成8个空格 """"""S.expandtabs([tabsize]) -> stringReturn 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 ""def find(self, sub, start=None, end=None):  """ 寻找子序列位置,如果没找到,返回 -1 """"""S.find(sub [,start [,end]]) -> intReturn the lowest index in S where substring sub is found,such that sub is contained within S[start:end].  Optionalarguments start and end are interpreted as in slice notation.Return -1 on failure."""return 0def format(*args, **kwargs): # known special case of str.format""" 字符串格式化,动态参数,将函数式编程时细说 """"""S.format(*args, **kwargs) -> stringReturn a formatted version of S, using substitutions from args and kwargs.The substitutions are identified by braces ('{' and '}')."""passdef index(self, sub, start=None, end=None):  """ 子序列位置,如果没找到,报错 """S.index(sub [,start [,end]]) -> intLike S.find() but raise ValueError when the substring is not found."""return 0def isalnum(self):  """ 是否是字母和数字 """"""S.isalnum() -> boolReturn True if all characters in S are alphanumericand there is at least one character in S, False otherwise."""return Falsedef isalpha(self):  """ 是否是字母 """"""S.isalpha() -> boolReturn True if all characters in S are alphabeticand there is at least one character in S, False otherwise."""return Falsedef isdigit(self):  """ 是否是数字 """"""S.isdigit() -> boolReturn True if all characters in S are digitsand there is at least one character in S, False otherwise."""return Falsedef islower(self):  """ 是否小写 """"""S.islower() -> boolReturn True if all cased characters in S are lowercase and there isat least one cased character in S, False otherwise."""return Falsedef isspace(self):  """S.isspace() -> boolReturn True if all characters in S are whitespaceand there is at least one character in S, False otherwise."""return Falsedef istitle(self):  """S.istitle() -> boolReturn True if S is a titlecased string and there is at least onecharacter in S, i.e. uppercase characters may only follow uncasedcharacters and lowercase characters only cased ones. Return Falseotherwise."""return Falsedef isupper(self):  """S.isupper() -> boolReturn True if all cased characters in S are uppercase and there isat least one cased character in S, False otherwise."""return Falsedef join(self, iterable):  """ 连接 """"""S.join(iterable) -> stringReturn a string which is the concatenation of the strings in theiterable.  The separator between elements is S."""return ""def ljust(self, width, fillchar=None):  """ 内容左对齐,右侧填充 """"""S.ljust(width[, fillchar]) -> stringReturn S left-justified in a string of length width. Padding isdone using the specified fill character (default is a space)."""return ""def lower(self):  """ 变小写 """"""S.lower() -> stringReturn a copy of the string S converted to lowercase."""return ""def lstrip(self, chars=None):  """ 移除左侧空白 """"""S.lstrip([chars]) -> string or unicodeReturn a copy of the string S with leading whitespace removed.If chars is given and not None, remove characters in chars instead.If chars is unicode, S will be converted to unicode before stripping"""return ""def partition(self, sep):  """ 分割,前,中,后三部分 """"""S.partition(sep) -> (head, sep, tail)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 notfound, return S and two empty strings."""passdef replace(self, old, new, count=None):  """ 替换 """"""S.replace(old, new[, count]) -> stringReturn a copy of string S with all occurrences of substringold replaced by new.  If the optional argument count isgiven, only the first count occurrences are replaced."""return ""def rfind(self, sub, start=None, end=None):  """S.rfind(sub [,start [,end]]) -> intReturn the highest index in S where substring sub is found,such that sub is contained within S[start:end].  Optionalarguments start and end are interpreted as in slice notation.Return -1 on failure."""return 0def rindex(self, sub, start=None, end=None):  """S.rindex(sub [,start [,end]]) -> intLike S.rfind() but raise ValueError when the substring is not found."""return 0def rjust(self, width, fillchar=None):  """S.rjust(width[, fillchar]) -> stringReturn S right-justified in a string of length width. Padding isdone using the specified fill character (default is a space)"""return ""def rpartition(self, sep):  """S.rpartition(sep) -> (head, sep, tail)Search for the separator sep in S, starting at the end of S, and returnthe part before it, the separator itself, and the part after it.  If theseparator is not found, return two empty strings and S."""passdef rsplit(self, sep=None, maxsplit=None):  """S.rsplit([sep [,maxsplit]]) -> list of stringsReturn a list of the words in the string S, using sep as thedelimiter string, starting at the end of the string and workingto the front.  If maxsplit is given, at most maxsplit splits aredone. If sep is not specified or is None, any whitespace stringis a separator."""return []def rstrip(self, chars=None):  """S.rstrip([chars]) -> string or unicodeReturn a copy of the string S with trailing whitespace removed.If chars is given and not None, remove characters in chars instead.If chars is unicode, S will be converted to unicode before stripping"""return ""def split(self, sep=None, maxsplit=None):  """ 分割, maxsplit最多分割几次 """"""S.split([sep [,maxsplit]]) -> list of stringsReturn a list of the words in the string S, using sep as thedelimiter string.  If maxsplit is given, at most maxsplitsplits are done. If sep is not specified or is None, anywhitespace string is a separator and empty strings are removedfrom the result."""return []def splitlines(self, keepends=False):  """ 根据换行分割 """"""S.splitlines(keepends=False) -> list of stringsReturn a list of the lines in S, breaking at line boundaries.Line breaks are not included in the resulting list unless keependsis given and true."""return []def startswith(self, prefix, start=None, end=None):  """ 是否起始 """"""S.startswith(prefix[, start[, end]]) -> boolReturn 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 Falsedef strip(self, chars=None):  """ 移除两段空白 """"""S.strip([chars]) -> string or unicodeReturn a copy of the string S with leading and trailingwhitespace removed.If chars is given and not None, remove characters in chars instead.If chars is unicode, S will be converted to unicode before stripping"""return ""def swapcase(self):  """ 大写变小写,小写变大写 """"""S.swapcase() -> stringReturn a copy of the string S with uppercase charactersconverted to lowercase and vice versa."""return ""def title(self):  """S.title() -> stringReturn a titlecased version of S, i.e. words start with uppercasecharacters, all remaining cased characters have lowercase."""return ""def translate(self, table, deletechars=None):  """转换,需要先做一个对应表,最后一个表示删除字符集合intab = "aeiou"outtab = "12345"trantab = maketrans(intab, outtab)str = "this is string example....wow!!!"print str.translate(trantab, 'xm')""""""S.translate(table [,deletechars]) -> stringReturn a copy of the string S, where all characters occurringin the optional argument deletechars are removed, and theremaining characters have been mapped through the giventranslation table, which must be a string of length 256 or None.If the table argument is None, no translation is applied andthe operation simply removes the characters in deletechars."""return ""def upper(self):  """S.upper() -> stringReturn a copy of the string S converted to uppercase."""return ""def zfill(self, width):  """方法返回指定长度的字符串,原字符串右对齐,前面填充0。""""""S.zfill(width) -> stringPad a numeric string S with zeros on the left, to fill a fieldof the specified width.  The string S is never truncated."""return ""def _formatter_field_name_split(self, *args, **kwargs): # real signature unknownpassdef _formatter_parser(self, *args, **kwargs): # real signature unknownpassdef __add__(self, y):  """ x.__add__(y) <==> x+y """passdef __contains__(self, y):  """ x.__contains__(y) <==> y in x """passdef __eq__(self, y):  """ x.__eq__(y) <==> x==y """passdef __format__(self, format_spec):  """S.__format__(format_spec) -> stringReturn a formatted version of S as described by format_spec."""return ""def __getattribute__(self, name):  """ x.__getattribute__('name') <==> x.name """passdef __getitem__(self, y):  """ x.__getitem__(y) <==> x[y] """passdef __getnewargs__(self, *args, **kwargs): # real signature unknownpassdef __getslice__(self, i, j):  """x.__getslice__(i, j) <==> x[i:j]Use of negative indices is not supported."""passdef __ge__(self, y):  """ x.__ge__(y) <==> x>=y """passdef __gt__(self, y):  """ x.__gt__(y) <==> x>y """passdef __hash__(self):  """ x.__hash__() <==> hash(x) """passdef __init__(self, string=''): # known special case of str.__init__"""str(object='') -> stringReturn a nice string representation of the object.If the argument is a string, the return value is the same object.# (copied from class doc)"""passdef __len__(self):  """ x.__len__() <==> len(x) """passdef __le__(self, y):  """ x.__le__(y) <==> x<=y """passdef __lt__(self, y):  """ x.__lt__(y) <==> x<y """passdef __mod__(self, y):  """ x.__mod__(y) <==> x%y """passdef __mul__(self, n):  """ x.__mul__(n) <==> x*n """pass@staticmethod # known case of __new__def __new__(S, *more):  """ T.__new__(S, ...) -> a new object with type S, a subtype of T """passdef __ne__(self, y):  """ x.__ne__(y) <==> x!=y """passdef __repr__(self):  """ x.__repr__() <==> repr(x) """passdef __rmod__(self, y):  """ x.__rmod__(y) <==> y%x """passdef __rmul__(self, n):  """ x.__rmul__(n) <==> n*x """passdef __sizeof__(self):  """ S.__sizeof__() -> size of S in memory, in bytes """passdef __str__(self):  """ x.__str__() <==> str(x) """pass

转载于:https://www.cnblogs.com/huangguabushihaogua/p/9219979.html

字符串类型str方法相关推荐

  1. python-for循环-数字类型-字符串类型str

    文章目录 一.for循环 二.数字类型 三.字符串类型str 一.for循环 while循环 vs for 循环 while循环:称之为条件循环,循环的次数取决于条件何时为False for循环:称之 ...

  2. python中str是什么_python的str()字符串类型的方法详解

    字符串一旦创建,不可修改,一旦修改或者拼接,都会造成重新生成字符串,因为内存存数据是一个挨着一个存的,如果增加一个字符串的话,之前的老位置只有一个地方,不够,这是原理性的东西,在其他语言里面也一样 7 ...

  3. python的str()字符串类型的方法详解

    字符串一旦创建,不可修改,一旦修改或者拼接,都会造成重新生成字符串,因为内存存数据是一个挨着一个存的,如果增加一个字符串的话,之前的老位置只有一个地方,不够,这是原理性的东西,在其他语言里面也一样 7 ...

  4. python字符串类型str_python数据类型之字符串类型str

    1.str 字符串 一:基本使用 #用途: 描述性质的数据 #定义方式 # name='egon' #name=str('egon') x=str(1.2) print(x,type(x)) 常用操作 ...

  5. python实现字符串类型 str 转换为 list 类型(unicode 转换为 list)

    在debug的时候发现了 type() 检测一个变量的时候,发现类型是unicode,然后自己需要的是list类型. 字符串如下: 但是不能用list()函数直接转换,因为直接转换就会使每一个字符都成 ...

  6. 18.Python字符串类型及常用内置方法

    文章目录 1.字符串 2.字符串的定义 3.打印引号 4.类型转换 5.索引取值 6.遍历 7.长度统计 8.字符串复制与拼接 8.1字符串的复制 8.2加号拼接 8.3join拼接 8.4字符截取拼 ...

  7. python:判断字符串类型方法

    str对象包括如下用于判断字符串类型的方法: str.isalnum():是否全为字母或数字 str.isalpha():是否全为字母 str.isdecimal():是否只含十进制数字符号 str. ...

  8. python中字符串类型的encode()方法_第五章 Python字符串常用方法详解

    5.1 Python字符串拼接(包含字符串拼接数字) 在 Python中拼接(连接)字符串很简单,可以直接将两个字符串紧挨着写在一起,具体格式为: strname = "str1" ...

  9. python字符串类型图解_Python基础——数据类型(图解+实例,非常详细!)

    内容及版权声明:笔记是根据开课吧--Python语法爬虫分析课和自己的理解记录,其中包含课程的截图,仅学习分享使用,如有侵权请私信删除! 目录 Python中常见的数据类型 变量:(相当于杯子可以往里 ...

最新文章

  1. 算法时间复杂度求解法【详细过程说明】
  2. mysql-mybatis 8.0版本配置====解决could not create connection to database server.
  3. 习题2.5 两个有序链表序列的合并 (15 分)
  4. Spring2.5的新特性
  5. windows7环境下的http-server的问题 排查
  6. pwm一个时间单位_RK3308——RGB调色灯三路PWM驱动
  7. 【Linux】一步一步学Linux——mesg命令(245)
  8. 字符串的规范使用(二)
  9. mkhd中的matrix
  10. python学习第29天
  11. [Ext JS]Grid的列过滤
  12. 找不到列 dbo 或用户定义的函数或聚合_Power BI 的大数据处理方案:聚合
  13. 基于stm32及sim800c sim868 实现的远程控制 小程序控制模块 源码 移植过程简介
  14. 练法、打法、演法——回味老罗踢馆这场戏
  15. 成为一名机器学习算法工程师,你需要这些必备技能
  16. 详解RS232、RS485、RS422、串口和握手
  17. 智能abc是什么输入法:win10可用的智能abc输入法免费下载
  18. VS2010/MFC编程入门教程之目录和总结(鸡啄米)
  19. spacy依存分析模型
  20. 记录一下学习嵌入式的方法和小窍门

热门文章

  1. 调用图片按钮的img图片
  2. Linux下mysql整库备份
  3. 训练(线段树+树状数组) poj——3264
  4. 首秀 Express 框架
  5. CommonJS,AMD,CMD区别 - 郑星阳 - ITeye博客
  6. vscode --- 快捷键格式化代码时,分号消失
  7. Spring3向Spring4升级过程中quartz修改
  8. 【QQ输入法】QQ输入法-剪切板 释放内存
  9. Difference: throw or throw ex?
  10. Codeforces Round #419 (Div. 2)