lesson3-字符串及其常用操作
生活随笔
收集整理的這篇文章主要介紹了
lesson3-字符串及其常用操作
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、常用操作
1、按索引取值(正向取+反向取) :只能取
>>> name = 'adc defg' >>> name[0] 'a'2、切片(顧頭不顧尾,步長)
>>> print(name[1:4]) 'dc '3、長度len
>>> len(name) 84、成員運算in和not in
>>> print('a' in name) >>> print('z' in name) True False5、移除空白strip
只能去開頭或者結尾的,中間的去不了
>>> str1 = "123abcrunoob321" >>> print (str1.strip( '2' )) >>> print (str1.strip( '1' )) >>> print (str1.strip( '123ab' )) 123abcrunoob321 23abcrunoob32 crunoo >>> str1 = " 3abcrunoob321" >>> print(str1) >>> print (str1.strip())3abcrunoob321 3abcrunoob321 >>> str2 = "\t AA\t\n" >>> print(str2) >>> print(str2.strip())AA AA >>> print(name.strip()) adc defg6、切分split
>>> print(name.split(' ')) >>> print(name.split('d')) ['adc', 'defg'] ['a', 'c ', 'efg']split,rsplit
split
7、循環
>>> for i in name: >>> print(i) a d cd e f g二、一般操作
8、lstrip,rstrip
去除左lstrip,去除右rstrip
str1 = " 3abcrunoob321 " >>> print(str1) >>> print (str1.strip()) >>> print(str1.lstrip())#lstrip只能去除開頭的3abcrunoob321 3abcrunoob321 3abcrunoob3219、lower,upper
大小寫
>>> name = 'aBc' >>> print(name) >>> print(name.lower()) >>> print(name.upper()) >aBc abc ABC10、startswith,endswith
Return True or Fulse
>>> na = 'abc' >>> print(na.startswith('a')) >>> print(na.endswith('bc')) >>> print(na.endswith('a')) True True False11、(%s) format
>>> res='{} {} {}'.format('egon',18,'male') >>> res1='{1} {0} {1}'.format('egon',18,'male') >>> res2='{name} {age} {sex}'.format(sex='male',name='egon',age=18) >>> print(res) >>> print(res) >>> print(res) 'egon 18 male' 18 egon 18 egon 18 male%s
>>> print("name is %s" %("Alfred1Xue")) 'name is Alfred1Xue'%d
>>> print(" %d years old." %(25)) 25 years old. >>>print ("%f m"%(1.70))#打印浮點數 1.700000 m >>> print ("is %.2f m"%(1.7011)) is 1.70 m12、join
join的對象必須都是字符串,將對象加到后面的字符串list中
>>> a = '||' >>> b = 'b' >>> print(a.join([b,'egon','say','hello','world'])) b||egon||say||hello||world13、isdigit
>>> #判斷字符是否為數字 >>> height = 'The One' >>> print(height.isdigit()) >>> print(height.istitle()) False True14、replace
將字符串中的某個字符/字符串替換成別的字符串
>>> name='japoierhjtanepgoijapogihj' >>> print(name.replace('a','SB',1)) jSBpoierhjtanepgoijapogihj三、其余操作
1、find,rfind,index,rindex,count
#S.find(sub[, start[, end]]) -> int #Return the lowest index in S where substring sub is found, >>> name='aushfoqsugb' >>> print(name.find('o',1,10)) #從頭開始找返回第一個,找不到則返回-1不會報錯,找到了則顯示索引 >>> print(name.rfind('s')) #從右邊開始找 5 7 >>> print(name.index('s'))#找不到會報錯,所以一般用find >>> print(name.rindex('s')) 2 7 print(name.count('u',1,3)) #顧頭不顧尾,如果不指定范圍則查找所有 1 >>> print(name.count('u')) 32、center,ljust,rjust,zfill
>>>name='agah' >>>print(name.center(30,'-'))#放中間,旁邊為'-' >>>print(name.ljust(30,'*'))#放左邊 >>>print(name.rjust(30,'*'))#放右邊 >>>print(name.zfill(50)) #用0填充 -------------agah------------- agah************************** **************************agah 0000000000000000000000000000000000000000000000agah3、expandtabs
>>>name='atweqr\thello\tasrtqa' >>>print(name) >>>print(name.expandtabs(1)) atweqr hello asrtqa atweqr hello asrtqa4、captalize,swapcase,title
>>>print(name.capitalize()) #首字母大寫 >>>print(name.swapcase()) #大小寫翻轉 >>>msg='open a bbq' >>>print(msg.title()) #每個單詞的首字母大寫 Atweqr hello asrtqa ATWEQR HELLO ASRTQA Open A Bbq5、is數字系列
6、is其他
原str類-python3
class str(object):"""str(object='') -> strstr(bytes_or_buffer[, encoding[, errors]]) -> strCreate a new string object from the given object. If encoding orerrors is specified, then the object must expose a data bufferthat will be decoded using the given encoding and error handler.Otherwise, returns the result of object.__str__() (if defined)or repr(object).encoding defaults to sys.getdefaultencoding().errors defaults to 'strict'."""def capitalize(self): # real signature unknown; restored from __doc__"""S.capitalize() -> strReturn a capitalized version of S, i.e. make the first characterhave upper case and the rest lower case."""return ""def casefold(self): # real signature unknown; restored from __doc__"""S.casefold() -> strReturn a version of S suitable for caseless comparisons."""return ""def center(self, width, fillchar=None): # real signature unknown; restored from __doc__"""S.center(width[, fillchar]) -> strReturn 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): # real signature unknown; restored from __doc__"""S.count(sub[, start[, end]]) -> intReturn the number of non-overlapping occurrences of substring sub instring S[start:end]. Optional arguments start and end areinterpreted as in slice notation."""return 0def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__"""S.encode(encoding='utf-8', errors='strict') -> bytesEncode S using the codec registered for encoding. Default encodingis 'utf-8'. 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 can handle UnicodeEncodeErrors."""return b""def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__"""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=8): # real signature unknown; restored from __doc__"""S.expandtabs(tabsize=8) -> strReturn 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): # real signature unknown; restored from __doc__"""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(self, *args, **kwargs): # known special case of str.format"""S.format(*args, **kwargs) -> strReturn a formatted version of S, using substitutions from args and kwargs.The substitutions are identified by braces ('{' and '}')."""passdef format_map(self, mapping): # real signature unknown; restored from __doc__"""S.format_map(mapping) -> strReturn a formatted version of S, using substitutions from mapping.The substitutions are identified by braces ('{' and '}')."""return ""def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__"""S.index(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.Raises ValueError when the substring is not found."""return 0def isalnum(self): # real signature unknown; restored from __doc__"""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): # real signature unknown; restored from __doc__"""S.isalpha() -> boolReturn True if all characters in S are alphabeticand there is at least one character in S, False otherwise."""return Falsedef isdecimal(self): # real signature unknown; restored from __doc__"""S.isdecimal() -> boolReturn True if there are only decimal characters in S,False otherwise."""return Falsedef isdigit(self): # real signature unknown; restored from __doc__"""S.isdigit() -> boolReturn True if all characters in S are digitsand there is at least one character in S, False otherwise."""return Falsedef isidentifier(self): # real signature unknown; restored from __doc__"""S.isidentifier() -> boolReturn True if S is a valid identifier accordingto the language definition.Use keyword.iskeyword() to test for reserved identifierssuch as "def" and "class"."""return Falsedef islower(self): # real signature unknown; restored from __doc__"""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 isnumeric(self): # real signature unknown; restored from __doc__"""S.isnumeric() -> boolReturn True if there are only numeric characters in S,False otherwise."""return Falsedef isprintable(self): # real signature unknown; restored from __doc__"""S.isprintable() -> boolReturn True if all characters in S are consideredprintable in repr() or S is empty, False otherwise."""return Falsedef isspace(self): # real signature unknown; restored from __doc__"""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): # real signature unknown; restored from __doc__"""S.istitle() -> boolReturn True if S is a titlecased string and there is at least onecharacter in S, i.e. upper- and titlecase characters may onlyfollow uncased characters and lowercase characters only cased ones.Return False otherwise."""return Falsedef isupper(self): # real signature unknown; restored from __doc__"""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): # real signature unknown; restored from __doc__"""S.join(iterable) -> strReturn a string which is the concatenation of the strings in theiterable. The separator between elements is S."""return ""def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__"""S.ljust(width[, fillchar]) -> strReturn S left-justified in a Unicode string of length width. Padding isdone using the specified fill character (default is a space)."""return ""def lower(self): # real signature unknown; restored from __doc__"""S.lower() -> strReturn a copy of the string S converted to lowercase."""return ""def lstrip(self, chars=None): # real signature unknown; restored from __doc__"""S.lstrip([chars]) -> strReturn a copy of the string S with leading whitespace removed.If chars is given and not None, remove characters in chars instead."""return ""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 Unicodeordinals (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, andin the resulting dictionary, each character in x will be mapped to thecharacter at the same position in y. If there is a third argument, itmust be a string, whose characters will be mapped to None in the result."""passdef partition(self, sep): # real signature unknown; restored from __doc__"""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): # real signature unknown; restored from __doc__"""S.replace(old, new[, count]) -> strReturn a copy of 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): # real signature unknown; restored from __doc__"""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): # real signature unknown; restored from __doc__"""S.rindex(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.Raises ValueError when the substring is not found."""return 0def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__"""S.rjust(width[, fillchar]) -> strReturn 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): # 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 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=-1): # real signature unknown; restored from __doc__"""S.rsplit(sep=None, maxsplit=-1) -> list of stringsReturn a list of the words in S, using sep as thedelimiter string, starting at the end of the string andworking to the front. If maxsplit is given, at most maxsplitsplits are done. If sep is not specified, any whitespace stringis a separator."""return []def rstrip(self, chars=None): # real signature unknown; restored from __doc__"""S.rstrip([chars]) -> strReturn a copy of the string S with trailing whitespace removed.If chars is given and not None, remove characters in chars instead."""return ""def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__"""S.split(sep=None, maxsplit=-1) -> list of stringsReturn a list of the words in 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 areremoved from the result."""return []def splitlines(self, keepends=None): # real signature unknown; restored from __doc__"""S.splitlines([keepends]) -> 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): # real signature unknown; restored from __doc__"""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): # real signature unknown; restored from __doc__"""S.strip([chars]) -> strReturn a copy of the string S with leading and trailingwhitespace removed.If chars is given and not None, remove characters in chars instead."""return ""def swapcase(self): # real signature unknown; restored from __doc__"""S.swapcase() -> strReturn a copy of S with uppercase characters converted to lowercaseand vice versa."""return ""def title(self): # real signature unknown; restored from __doc__"""S.title() -> strReturn a titlecased version of S, i.e. words start with title casecharacters, all remaining cased characters have lower case."""return ""def translate(self, table): # real signature unknown; restored from __doc__"""S.translate(table) -> strReturn a copy of the string S in which each character has been mappedthrough the given translation table. The table must implementlookup/indexing via __getitem__, for instance a dictionary or list,mapping Unicode ordinals to Unicode ordinals, strings, or None. Ifthis operation raises LookupError, the character is left untouched.Characters mapped to None are deleted."""return ""def upper(self): # real signature unknown; restored from __doc__"""S.upper() -> strReturn a copy of S converted to uppercase."""return ""def zfill(self, width): # real signature unknown; restored from __doc__"""S.zfill(width) -> strPad a numeric string S with zeros on the left, to fill a fieldof the specified width. The string S is never truncated."""return ""def __add__(self, *args, **kwargs): # real signature unknown""" Return self+value. """passdef __contains__(self, *args, **kwargs): # real signature unknown""" Return key in self. """passdef __eq__(self, *args, **kwargs): # real signature unknown""" Return self==value. """passdef __format__(self, format_spec): # real signature unknown; restored from __doc__"""S.__format__(format_spec) -> strReturn a formatted version of S as described by format_spec."""return ""def __getattribute__(self, *args, **kwargs): # real signature unknown""" Return getattr(self, name). """passdef __getitem__(self, *args, **kwargs): # real signature unknown""" Return self[key]. """passdef __getnewargs__(self, *args, **kwargs): # real signature unknownpassdef __ge__(self, *args, **kwargs): # real signature unknown""" Return self>=value. """passdef __gt__(self, *args, **kwargs): # real signature unknown""" Return self>value. """passdef __hash__(self, *args, **kwargs): # real signature unknown""" Return hash(self). """passdef __init__(self, value='', encoding=None, errors='strict'): # known special case of str.__init__"""str(object='') -> strstr(bytes_or_buffer[, encoding[, errors]]) -> strCreate a new string object from the given object. If encoding orerrors is specified, then the object must expose a data bufferthat will be decoded using the given encoding and error handler.Otherwise, returns the result of object.__str__() (if defined)or repr(object).encoding defaults to sys.getdefaultencoding().errors defaults to 'strict'.# (copied from class doc)"""passdef __iter__(self, *args, **kwargs): # real signature unknown""" Implement iter(self). """passdef __len__(self, *args, **kwargs): # real signature unknown""" Return len(self). """passdef __le__(self, *args, **kwargs): # real signature unknown""" Return self<=value. """passdef __lt__(self, *args, **kwargs): # real signature unknown""" Return self<value. """passdef __mod__(self, *args, **kwargs): # real signature unknown""" Return self%value. """passdef __mul__(self, *args, **kwargs): # real signature unknown""" Return self*value.n """pass@staticmethod # known case of __new__def __new__(*args, **kwargs): # real signature unknown""" Create and return a new object. See help(type) for accurate signature. """passdef __ne__(self, *args, **kwargs): # real signature unknown""" Return self!=value. """passdef __repr__(self, *args, **kwargs): # real signature unknown""" Return repr(self). """passdef __rmod__(self, *args, **kwargs): # real signature unknown""" Return value%self. """passdef __rmul__(self, *args, **kwargs): # real signature unknown""" Return self*value. """passdef __sizeof__(self): # real signature unknown; restored from __doc__""" S.__sizeof__() -> size of S in memory, in bytes """passdef __str__(self, *args, **kwargs): # real signature unknown""" Return str(self). """pass總結
以上是生活随笔為你收集整理的lesson3-字符串及其常用操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: for、enumerat、range、x
- 下一篇: tensorflow对应的cudnn、c