1.1 python数据类型之str类

Posted rodger

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1.1 python数据类型之str类相关的知识,希望对你有一定的参考价值。

类名str

基本操作

  • 切片 [开始位置:结束位置(:步长)]

      s = "hello,world!"  

        取前两个字符 s = [0:2]   0可以省略,切片取头不取尾

        反转字符串 s = [-1 : : -1]

        取整个字符串 s = [ : ]  后面什么都不写默认取完

  • 索引 [索引值]   注:不支持索引修改字符串值,会报错

        索引值的范围是0-字符串长度减一,超过这个范围会报错(IndexError: string index out of range) 

  • 各种方法函数:

 

  1     def capitalize(self): # real signature unknown; restored from __doc__  #将字符串首字母大写,其余小写
  2         """
  3         S.capitalize() -> str
  4         
  5         Return a capitalized version of S, i.e. make the first character
  6         have upper case and the rest lower case.
  7         """
  8         return ""
  9 
 10     def casefold(self): # real signature unknown; restored from __doc__   #将不分语种的字符串全部小写
 11         """
 12         S.casefold() -> str
 13         
 14         Return a version of S suitable for caseless comparisons.
 15         """
 16         return ""
 17 
 18     def center(self, width, fillchar=None): # real signature unknown; restored from __doc__  将字符串填入width长的字符中间,并将其余字符用fillchar填充
 19         """
 20         S.center(width[, fillchar]) -> str
 21         
 22         Return S centered in a string of length width. Padding is
 23         done using the specified fill character (default is a space)
 24         """
 25         return ""
 26 
 27     def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__   返回sub子序列在字符串指定位置中出现次数,start开始位置,end结束位置
 28         """
 29         S.count(sub[, start[, end]]) -> int
 30         
 31         Return the number of non-overlapping occurrences of substring sub in
 32         string S[start:end].  Optional arguments start and end are
 33         interpreted as in slice notation.
 34         """
 35         return 0
 36 
 37     def encode(self, encoding=utf-8, errors=strict): # real signature unknown; restored from __doc__ 改变编码格式 默认utf-8
 38         """
 39         S.encode(encoding=‘utf-8‘, errors=‘strict‘) -> bytes
 40         
 41         Encode S using the codec registered for encoding. Default encoding
 42         is ‘utf-8‘. errors may be given to set a different error
 43         handling scheme. Default is ‘strict‘ meaning that encoding errors raise
 44         a UnicodeEncodeError. Other possible values are ‘ignore‘, ‘replace‘ and
 45         ‘xmlcharrefreplace‘ as well as any other name registered with
 46         codecs.register_error that can handle UnicodeEncodeErrors.
 47         """
 48         return b""
 49 
 50     def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__  判断字符串是否以suffix子序列结尾,strat开始,end结束
 51         """
 52         S.endswith(suffix[, start[, end]]) -> bool
 53         
 54         Return True if S ends with the specified suffix, False otherwise.
 55         With optional start, test S beginning at that position.
 56         With optional end, stop comparing S at that position.
 57         suffix can also be a tuple of strings to try.
 58         """
 59         return False
 60 
 61     def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__   指定制表符/t占有位数,tabsize指定占有位数
 62         """
 63         S.expandtabs(tabsize=8) -> str
 64         
 65         Return a copy of S where all tab characters are expanded using spaces.
 66         If tabsize is not given, a tab size of 8 characters is assumed.
 67         """
 68         return ""
 69 
 70     def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__   返回在字符串中最先出现的子序列的索引号,如果不存在返回-1
 71         """
 72         S.find(sub[, start[, end]]) -> int
 73         
 74         Return the lowest index in S where substring sub is found,
 75         such that sub is contained within S[start:end].  Optional
 76         arguments start and end are interpreted as in slice notation.
 77         
 78         Return -1 on failure.
 79         """
 80         return 0
 81 
 82     def format(self, *args, **kwargs): # known special case of str.format    字符串格式化
 83         """
 84         S.format(*args, **kwargs) -> str
 85         
 86         Return a formatted version of S, using substitutions from args and kwargs.
 87         The substitutions are identified by braces (‘{‘ and ‘}‘).
 88         """
 89         pass
 90 
 91     def format_map(self, mapping): # real signature unknown; restored from __doc__    字符串格式化,指定mapping格式
 92         """
 93         S.format_map(mapping) -> str
 94         
 95         Return a formatted version of S, using substitutions from mapping.
 96         The substitutions are identified by braces (‘{‘ and ‘}‘).
 97         """
 98         return ""
 99 
100     def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__   返回子序列的索引,无则报错
101         """
102         S.index(sub[, start[, end]]) -> int
103         
104         Return the lowest index in S where substring sub is found, 
105         such that sub is contained within S[start:end].  Optional
106         arguments start and end are interpreted as in slice notation.
107         
108         Raises ValueError when the substring is not found.
109         """
110         return 0
111 
112     def isalnum(self): # real signature unknown; restored from __doc__      判断是否全是数字、字母
113         """
114         S.isalnum() -> bool
115         
116         Return True if all characters in S are alphanumeric
117         and there is at least one character in S, False otherwise.
118         """
119         return False
120 
121     def isalpha(self): # real signature unknown; restored from __doc__   判断是否全是字母
122         """
123         S.isalpha() -> bool
124         
125         Return True if all characters in S are alphabetic
126         and there is at least one character in S, False otherwise.
127         """
128         return False
129 
130     def isdecimal(self): # real signature unknown; restored from __doc__  判断是否全是十进制数字
131         """
132         S.isdecimal() -> bool
133         
134         Return True if there are only decimal characters in S,
135         False otherwise.
136         """
137         return False
138 
139     def isdigit(self): # real signature unknown; restored from __doc__   判断是否全是数字
140         """
141         S.isdigit() -> bool
142         
143         Return True if all characters in S are digits
144         and there is at least one character in S, False otherwise.
145         """
146         return False
147 
148     def isidentifier(self): # real signature unknown; restored from __doc__  判断是否是有效标识符,用来判断变量命名是否合法
149         """
150         S.isidentifier() -> bool
151         
152         Return True if S is a valid identifier according
153         to the language definition.
154         
155         Use keyword.iskeyword() to test for reserved identifiers
156         such as "def" and "class".
157         """
158         return False
159 
160     def islower(self): # real signature unknown; restored from __doc__   判断是否全是小写
161         """
162         S.islower() -> bool
163         
164         Return True if all cased characters in S are lowercase and there is
165         at least one cased character in S, False otherwise.
166         """
167         return False
168 
169     def isnumeric(self): # real signature unknown; restored from __doc__   判断是否全是数字
170         """
171         S.isnumeric() -> bool
172         
173         Return True if there are only numeric characters in S,
174         False otherwise.
175         """
176         return False
177 
178     def isprintable(self): # real signature unknown; restored from __doc__   判断是否全可以打印
179         """
180         S.isprintable() -> bool
181         
182         Return True if all characters in S are considered
183         printable in repr() or S is empty, False otherwise.
184         """
185         return False
186 
187     def isspace(self): # real signature unknown; restored from __doc__   判断是否全是空格、换行符、制表符
188         """
189         S.isspace() -> bool
190         
191         Return True if all characters in S are whitespace
192         and there is at least one character in S, False otherwise.
193         """
194         return False
195 
196     def istitle(self): # real signature unknown; restored from __doc__   判断是否是标题字符
197         """
198         S.istitle() -> bool
199         
200         Return True if S is a titlecased string and there is at least one
201         character in S, i.e. upper- and titlecase characters may only
202         follow uncased characters and lowercase characters only cased ones.
203         Return False otherwise.
204         """
205         return False
206 
207     def isupper(self): # real signature unknown; restored from __doc__  判断是否全是大写
208         """
209         S.isupper() -> bool
210         
211         Return True if all cased characters in S are uppercase and there is
212         at least one cased character in S, False otherwise.
213         """
214         return False
215 
216     def join(self, iterable): # real signature unknown; restored from __doc__  生成一个由指定字符串填充连接可迭代字符的字符串
217         """
218         S.join(iterable) -> str
219         
220         Return a string which is the concatenation of the strings in the
221         iterable.  The separator between elements is S.
222         """
223         return ""
224 
225     def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__  内容左对齐,右侧填充,默认空格,可选fillchar
226         """
227         S.ljust(width[, fillchar]) -> str
228         
229         Return S left-justified in a Unicode string of length width. Padding is
230         done using the specified fill character (default is a space).
231         """
232         return ""
233 
234     def lower(self): # real signature unknown; restored from __doc__   将字符串中的所有英文字母小写
235         """
236         S.lower() -> str
237         
238         Return a copy of the string S converted to lowercase.
239         """
240         return ""
241 
242     def lstrip(self, chars=None): # real signature unknown; restored from __doc__  移除左侧空格
243         """
244         S.lstrip([chars]) -> str
245         
246         Return a copy of the string S with leading whitespace removed.
247         If chars is given and not None, remove characters in chars instead.
248         """
249         return ""
250 
251     def maketrans(self, *args, **kwargs): # real signature unknown     创建字符映射的转换表
252         """
253         Return a translation table usable for str.translate().
254         
255         If there is only one argument, it must be a dictionary mapping Unicode
256         ordinals (integers) or characters to Unicode ordinals, strings or None.
257         Character keys will be then converted to ordinals.
258         If there are two arguments, they must be strings of equal length, and
259         in the resulting dictionary, each character in x will be mapped to the
260         character at the same position in y. If there is a third argument, it
261         must be a string, whose characters will be mapped to None in the result.
262         """
263         pass
264 
265     def partition(self, sep): # real signature unknown; restored from __doc__   将字符串分成三部分:sep序列、sep前序列、sep后序列
266         """
267         S.partition(sep) -> (head, sep, tail)
268         
269         Search for the separator sep in S, and return the part before it,
270         the separator itself, and the part after it.  If the separator is not
271         found, return S and two empty strings.
272         """
273         pass
274 
275     def replace(self, old, new, count=None): # real signature unknown; restored from __doc__   替换字符,count指定替换次数
276         """
277         S.replace(old, new[, count]) -> str
278         
279         Return a copy of S with all occurrences of substring
280         old replaced by new.  If the optional argument count is
281         given, only the first count occurrences are replaced.
282         """
283         return ""
284 
285     def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__  返回从右往左查找子序列的索引,没找到返回-1
286         """
287         S.rfind(sub[, start[, end]]) -> int
288         
289         Return the highest index in S where substring sub is found,
290         such that sub is contained within S[start:end].  Optional
291         arguments start and end are interpreted as in slice notation.
292         
293         Return -1 on failure.
294         """
295         return 0
296 
297     def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__  从右边开始查找子序列,没找到报错
298         """
299         S.rindex(sub[, start[, end]]) -> int
300         
301         Return the highest index in S where substring sub is found,
302         such that sub is contained within S[start:end].  Optional
303         arguments start and end are interpreted as in slice notation.
304         
305         Raises ValueError when the substring is not found.
306         """
307         return 0
308 
309     def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__  内容右对齐,左侧填充
310         """
311         S.rjust(width[, fillchar]) -> str
312         
313         Return S right-justified in a string of length width. Padding is
314         done using the specified fill character (default is a space).
315         """
316         return ""
317 
318     def rpartition(self, sep): # real signature unknown; restored from __doc__   从右边开始,将字符串分成三部分,sep、sep后】sep前
319         """
320         S.rpartition(sep) -> (head, sep, tail)
321         
322         Search for the separator sep in S, starting at the end of S, and return
323         the part before it, the separator itself, and the part after it.  If the
324         separator is not found, return two empty strings and S.
325         """
326         pass
327 
328     def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__  从右边开始返回按指定分隔符切割指定次数字符串的list
329         """
330         S.rsplit(sep=None, maxsplit=-1) -> list of strings
331         
332         Return a list of the words in S, using sep as the
333         delimiter string, starting at the end of the string and
334         working to the front.  If maxsplit is given, at most maxsplit
335         splits are done. If sep is not specified, any whitespace string
336         is a separator.
337         """
338         return []
339 
340     def rstrip(self, chars=None): # real signature unknown; restored from __doc__  移除右侧空白
341         """
342         S.rstrip([chars]) -> str
343         
344         Return a copy of the string S with trailing whitespace removed.
345         If chars is given and not None, remove characters in chars instead.
346         """
347         return ""
348 
349     def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__  按指定分隔符切割字符串,maxsplit指定切割次数,从左往右
350         """
351         S.split(sep=None, maxsplit=-1) -> list of strings
352         
353         Return a list of the words in S, using sep as the
354         delimiter string.  If maxsplit is given, at most maxsplit
355         splits are done. If sep is not specified or is None, any
356         whitespace string is a separator and empty strings are
357         removed from the result.
358         """
359         return []
360 
361     def splitlines(self, keepends=None): # real signature unknown; restored from __doc__ 根据换行符分割字符串
362         """
363         S.splitlines([keepends]) -> list of strings
364         
365         Return a list of the lines in S, breaking at line boundaries.
366         Line breaks are not included in the resulting list unless keepends
367         is given and true.
368         """
369         return []
370 
371     def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__  判断是否以子序列开头
372         """
373         S.startswith(prefix[, start[, end]]) -> bool
374         
375         Return True if S starts with the specified prefix, False otherwise.
376         With optional start, test S beginning at that position.
377         With optional end, stop comparing S at that position.
378         prefix can also be a tuple of strings to try.
379         """
380         return False
381 
382     def strip(self, chars=None): # real signature unknown; restored from __doc__   去除首尾空格
383         """
384         S.strip([chars]) -> str
385         
386         Return a copy of the string S with leading and trailing
387         whitespace removed.
388         If chars is given and not None, remove characters in chars instead.
389         """
390         return ""
391 
392     def swapcase(self): # real signature unknown; restored from __doc__  大写变小写,小写变大写
393         """
394         S.swapcase() -> str
395         
396         Return a copy of S with uppercase characters converted to lowercase
397         and vice versa.
398         """
399         return ""
400 
401     def title(self): # real signature unknown; restored from __doc__  将字符串变为title字符
402         """
403         S.title() -> str
404         
405         Return a titlecased version of S, i.e. words start with title case
406         characters, all remaining cased characters have lower case.
407         """
408         return ""
409 
410     def translate(self, table): # real signature unknown; restored from __doc__  转换字符,按照table规则
#intab = "aeiou"
#outtab = "12345"
#trantab = str.maketrans(intab, outtab)
#s = "this is string example....wow!!!"
#print(s.translate(trantab)
411         """
412         S.translate(table) -> str
413         
414         Return a copy of the string S in which each character has been mapped
415         through the given translation table. The table must implement
416         lookup/indexing via __getitem__, for instance a dictionary or list,
417         mapping Unicode ordinals to Unicode ordinals, strings, or None. If
418         this operation raises LookupError, the character is left untouched.
419         Characters mapped to None are deleted.
420         """
421         return ""
422 
423     def upper(self): # real signature unknown; restored from __doc__  大写
424         """
425         S.upper() -> str
426         
427         Return a copy of S converted to uppercase.
428         """
429         return ""
430 
431     def zfill(self, width): # real signature unknown; restored from __doc__  返回指定长度字符串,原字符串右对齐,左侧填0
432         """
433         S.zfill(width) -> str
434         
435         Pad a numeric string S with zeros on the left, to fill a field
436         of the specified width. The string S is never truncated.
437         """
438         return ""
  1    def __add__(self, *args, **kwargs):  # real signature unknown
  2         """ 字符串的加法运算 """
  3         """ Return self+value. """
  4         pass
  5 
  6     def __contains__(self, *args, **kwargs):  # real signature unknown
  7         """ 是否包含 """
  8         """ Return key in self. """
  9         pass
 10 
 11     def __eq__(self, *args, **kwargs):  # real signature unknown
 12         """ 比较前后两个字符串是否相等 """
 13         """ Return self==value. """
 14         pass
 15 
 16     def __format__(self, format_spec):  # real signature unknown; restored from __doc__
 17         """ 字符串格式化 """
 18         """
 19         S.__format__(format_spec) -> str
 20 
 21         Return a formatted version of S as described by format_spec.
 22         """
 23         return ""
 24 
 25     def __getattribute__(self, *args, **kwargs):  # real signature unknown
 26         """ x.__getattribute__(‘name‘) <==> x.name """
 27         """ Return getattr(self, name). """
 28         pass
 29 
 30     def __getitem__(self, *args, **kwargs):  # real signature unknown
 31         """ 根据索引取值 x.____getitem__(y) <==> x[y] """
 32         """ Return self[key]. """
 33         pass
 34 
 35     def __getnewargs__(self, *args, **kwargs):  # real signature unknown
 36         """ 内部调用__new__或创建对象时传入参数使用 """
 37         pass
 38 
 39     def __ge__(self, *args, **kwargs):  # real signature unknown
 40         """ 比较左边的字符串的ascii码值是否大于等于右边的ascii码值 """
 41         """ Return self>=value. """
 42         pass
 43 
 44     def __gt__(self, *args, **kwargs):  # real signature unknown
 45         """ 比较左边的字符串的ascii码值是否大于右边的ascii码值 """
 46         """ Return self>value. """
 47         pass
 48 
 49     def __hash__(self, *args, **kwargs):  # real signature unknown
 50         """ 返回字符串的哈希值 """
 51         """ Return hash(self). """
 52         pass
 53 
 54     def __init__(self, value=‘‘, encoding=None, errors=strict):  # known special case of str.__init__
 55         """ 构造方法,创建string对象时调用 """
 56         """
 57         str(object=‘‘) -> str
 58         str(bytes_or_buffer[, encoding[, errors]]) -> str
 59 
 60         Create a new string object from the given object. If encoding or
 61         errors is specified, then the object must expose a data buffer
 62         that will be decoded using the given encoding and error handler.
 63         Otherwise, returns the result of object.__str__() (if defined)
 64         or repr(object).
 65         encoding defaults to sys.getdefaultencoding().
 66         errors defaults to ‘strict‘.
 67         # (copied from class doc)
 68         """
 69         pass
 70 
 71     def __iter__(self, *args, **kwargs):  # real signature unknown
 72         """ 返回迭代器对象 """
 73         """ Implement iter(self). """
 74         pass
 75 
 76     def __len__(self, *args, **kwargs):  # real signature unknown
 77         """ 返回字符串的长度 """
 78         """ Return len(self). """
 79         pass
 80 
 81     def __le__(self, *args, **kwargs):  # real signature unknown
 82         """ 比较左边的字符串的ascii码值是否小于等于右边的ascii码值 """
 83         """ Return self<=value. """
 84         pass
 85 
 86     def __lt__(self, *args, **kwargs):  # real signature unknown
 87         """ 比较左边的字符串的ascii码值是否小于右边的ascii码值 """
 88         """ Return self<value. """
 89         pass
 90 
 91     def __mod__(self, *args, **kwargs):  # real signature unknown
 92         """ Return self%value. """
 93         pass
 94 
 95     def __mul__(self, *args, **kwargs):  # real signature unknown
 96         """ 字符串的惩罚运算 """
 97         """ Return self*value.n """
 98 
 99         pass
100 
101     @staticmethod  # known case of __new__
102     def __new__(*args, **kwargs):  # real signature unknown
103         """ Create and return a new object.  See help(type) for accurate signature. """
104         pass
105 
106     def __ne__(self, *args, **kwargs):  # real signature unknown
107         """ x.__ne__(y) 如果x与y的值不相等,返回True,相等则返回False """
108         """ Return self!=value. """
109         pass
110 
111     def __repr__(self, *args, **kwargs):  # real signature unknown
112         """ 转化为解释器可读取的形式 """
113         """ Return repr(self). """
114         pass
115 
116     def __rmod__(self, *args, **kwargs):  # real signature unknown
117         """ Return value%self. """
118         pass
119 
120     def __rmul__(self, *args, **kwargs):  # real signature unknown
121         """ 字符串的乘法运算 """
122         """ Return self*value. """
123         pass
124 
125     def __sizeof__(self):  # real signature unknown; restored from __doc__
126         """ 返回在内存中占用的字节数 """
127         """ S.__sizeof__() -> size of S in memory, in bytes """
128         pass
129 
130     def __str__(self, *args, **kwargs):  # real signature unknown
131         """ 转化成可读取的形式 """
132         """ Return str(self). """
133         pass

 

 

 

  

以上是关于1.1 python数据类型之str类的主要内容,如果未能解决你的问题,请参考以下文章

Python之基本数据类型 基本运算

python之数据类型补充集合深浅copy

python基础之基本数据类型

python基础之基本数据类型

Python数据类型的内置函数之str(字符串)

python基础之数据类型转换