字符串类型str方法
首字母大寫
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方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 小程序 获取用户信息 openid 等
- 下一篇: system 无法以 sysdba 登录