1.字符串表达

'hello python'
"hello world"

2.字符串功能

  1 class str(object):
  2     """
  3     str(object='') -> str
  4     str(bytes_or_buffer[, encoding[, errors]]) -> str
  5     
  6     Create a new string object from the given object. If encoding or
  7     errors is specified, then the object must expose a data buffer
  8     that will be decoded using the given encoding and error handler.
  9     Otherwise, returns the result of object.__str__() (if defined)
 10     or repr(object).
 11     encoding defaults to sys.getdefaultencoding().
 12     errors defaults to 'strict'.
 13     """
 14     def capitalize(self): # real signature unknown; restored from __doc__
 15         """
 16         S.capitalize() -> str
 17         
 18         Return a capitalized version of S, i.e. make the first character
 19         have upper case and the rest lower case.
 20         """
 21         return ""
 22 
 23     def casefold(self): # real signature unknown; restored from __doc__
 24         """
 25         S.casefold() -> str
 26         
 27         Return a version of S suitable for caseless comparisons.
 28         """
 29         return ""
 30 
 31     def center(self, width, fillchar=None): # real signature unknown; restored from __doc__
 32         """
 33         S.center(width[, fillchar]) -> str
 34         
 35         Return S centered in a string of length width. Padding is
 36         done using the specified fill character (default is a space)
 37         """
 38         return ""
 39 
 40     def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
 41         """
 42         S.count(sub[, start[, end]]) -> int
 43         
 44         Return the number of non-overlapping occurrences of substring sub in
 45         string S[start:end].  Optional arguments start and end are
 46         interpreted as in slice notation.
 47         """
 48         return 0
 49 
 50     def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__
 51         """
 52         S.encode(encoding='utf-8', errors='strict') -> bytes
 53         
 54         Encode S using the codec registered for encoding. Default encoding
 55         is 'utf-8'. errors may be given to set a different error
 56         handling scheme. Default is 'strict' meaning that encoding errors raise
 57         a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
 58         'xmlcharrefreplace' as well as any other name registered with

 59         codecs.register_error that can handle UnicodeEncodeErrors.
 60         """
 61         return b""
 62 
 63     def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
 64         """
 65         S.endswith(suffix[, start[, end]]) -> bool
 66         
 67         Return True if S ends with the specified suffix, False otherwise.
 68         With optional start, test S beginning at that position.
 69         With optional end, stop comparing S at that position.
 70         suffix can also be a tuple of strings to try.
 71         """
 72         return False
 73 
 74     def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__
 75         """
 76         S.expandtabs(tabsize=8) -> str
 77         
 78         Return a copy of S where all tab characters are expanded using spaces.
 79         If tabsize is not given, a tab size of 8 characters is assumed.
 80         """
 81         return ""
 82 
 83     def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
 84         """
 85         S.find(sub[, start[, end]]) -> int
 86         
 87         Return the lowest index in S where substring sub is found,
 88         such that sub is contained within S[start:end].  Optional
 89         arguments start and end are interpreted as in slice notation.
 90         
 91         Return -1 on failure.
 92         """
 93         return 0
 94 
 95     def format(self, *args, **kwargs): # known special case of str.format
 96         """
 97         S.format(*args, **kwargs) -> str
 98         
 99         Return a formatted version of S, using substitutions from args and kwargs.
100         The substitutions are identified by braces ('{' and '}').
101         """
102         pass
103 
104     def format_map(self, mapping): # real signature unknown; restored from __doc__
105         """
106         S.format_map(mapping) -> str
107         
108         Return a formatted version of S, using substitutions from mapping.
109         The substitutions are identified by braces ('{' and '}').
110         """
111         return ""
112 
113     def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
114         """
115         S.index(sub[, start[, end]]) -> int
116         
117         Like S.find() but raise ValueError when the substring is not found.
118         """
119         return 0
120 
121     def isalnum(self): # real signature unknown; restored from __doc__
122         """
123         S.isalnum() -> bool
124         
125         Return True if all characters in S are alphanumeric
126         and there is at least one character in S, False otherwise.
127         """
128         return False
129 
130     def isalpha(self): # real signature unknown; restored from __doc__
131         """
132         S.isalpha() -> bool
133         
134         Return True if all characters in S are alphabetic
135         and there is at least one character in S, False otherwise.
136         """
137         return False
138 
139     def isdecimal(self): # real signature unknown; restored from __doc__
140         """
141         S.isdecimal() -> bool
142         
143         Return True if there are only decimal characters in S,
144         False otherwise.
145         """
146         return False
147 
148     def isdigit(self): # real signature unknown; restored from __doc__
149         """
150         S.isdigit() -> bool
151         
152         Return True if all characters in S are digits
153         and there is at least one character in S, False otherwise.
154         """
155         return False
156 
157     def isidentifier(self): # real signature unknown; restored from __doc__
158         """
159         S.isidentifier() -> bool
160         
161         Return True if S is a valid identifier according
162         to the language definition.
163         
164         Use keyword.iskeyword() to test for reserved identifiers
165         such as "def" and "class".
166         """
167         return False
168 
169     def islower(self): # real signature unknown; restored from __doc__
170         """
171         S.islower() -> bool
172         
173         Return True if all cased characters in S are lowercase and there is
174         at least one cased character in S, False otherwise.
175         """
176         return False
177 
178     def isnumeric(self): # real signature unknown; restored from __doc__
179         """
180         S.isnumeric() -> bool
181         
182         Return True if there are only numeric characters in S,
183         False otherwise.
184         """
185         return False
186 
187     def isprintable(self): # real signature unknown; restored from __doc__
188         """
189         S.isprintable() -> bool
190         
191         Return True if all characters in S are considered
192         printable in repr() or S is empty, False otherwise.
193         """
194         return False
195 
196     def isspace(self): # real signature unknown; restored from __doc__
197         """
198         S.isspace() -> bool
199         
200         Return True if all characters in S are whitespace
201         and there is at least one character in S, False otherwise.
202         """
203         return False
204 
205     def istitle(self): # real signature unknown; restored from __doc__
206         """
207         S.istitle() -> bool
208         
209         Return True if S is a titlecased string and there is at least one
210         character in S, i.e. upper- and titlecase characters may only
211         follow uncased characters and lowercase characters only cased ones.
212         Return False otherwise.
213         """
214         return False
215 
216     def isupper(self): # real signature unknown; restored from __doc__
217         """
218         S.isupper() -> bool
219         
220         Return True if all cased characters in S are uppercase and there is
221         at least one cased character in S, False otherwise.
222         """
223         return False
224 
225     def join(self, iterable): # real signature unknown; restored from __doc__
226         """
227         S.join(iterable) -> str
228         
229         Return a string which is the concatenation of the strings in the
230         iterable.  The separator between elements is S.
231         """
232         return ""
233 
234     def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__
235         """
236         S.ljust(width[, fillchar]) -> str
237         
238         Return S left-justified in a Unicode string of length width. Padding is
239         done using the specified fill character (default is a space).
240         """
241         return ""
242 
243     def lower(self): # real signature unknown; restored from __doc__
244         """
245         S.lower() -> str
246         
247         Return a copy of the string S converted to lowercase.
248         """
249         return ""
250 
251     def lstrip(self, chars=None): # real signature unknown; restored from __doc__
252         """
253         S.lstrip([chars]) -> str
254         
255         Return a copy of the string S with leading whitespace removed.
256         If chars is given and not None, remove characters in chars instead.
257         """
258         return ""
259 
260     def maketrans(self, *args, **kwargs): # real signature unknown
261         """
262         Return a translation table usable for str.translate().
263         
264         If there is only one argument, it must be a dictionary mapping Unicode
265         ordinals (integers) or characters to Unicode ordinals, strings or None.
266         Character keys will be then converted to ordinals.
267         If there are two arguments, they must be strings of equal length, and
268         in the resulting dictionary, each character in x will be mapped to the
269         character at the same position in y. If there is a third argument, it
270         must be a string, whose characters will be mapped to None in the result.
271         """
272         pass
273 
274     def partition(self, sep): # real signature unknown; restored from __doc__
275         """
276         S.partition(sep) -> (head, sep, tail)
277         
278         Search for the separator sep in S, and return the part before it,
279         the separator itself, and the part after it.  If the separator is not
280         found, return S and two empty strings.
281         """
282         pass
283 
284     def replace(self, old, new, count=None): # real signature unknown; restored from __doc__
285         """
286         S.replace(old, new[, count]) -> str
287         
288         Return a copy of S with all occurrences of substring
289         old replaced by new.  If the optional argument count is
290         given, only the first count occurrences are replaced.
291         """
292         return ""
293 
294     def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
295         """
296         S.rfind(sub[, start[, end]]) -> int
297         
298         Return the highest index in S where substring sub is found,
299         such that sub is contained within S[start:end].  Optional
300         arguments start and end are interpreted as in slice notation.
301         
302         Return -1 on failure.
303         """
304         return 0
305 
306     def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
307         """
308         S.rindex(sub[, start[, end]]) -> int
309         
310         Like S.rfind() but raise ValueError when the substring is not found.
311         """
312         return 0
313 
314     def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__
315         """
316         S.rjust(width[, fillchar]) -> str
317         
318         Return S right-justified in a string of length width. Padding is
319         done using the specified fill character (default is a space).
320         """
321         return ""
322 
323     def rpartition(self, sep): # real signature unknown; restored from __doc__
324         """
325         S.rpartition(sep) -> (head, sep, tail)
326         
327         Search for the separator sep in S, starting at the end of S, and return
328         the part before it, the separator itself, and the part after it.  If the
329         separator is not found, return two empty strings and S.
330         """
331         pass
332 
333     def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
334         """
335         S.rsplit(sep=None, maxsplit=-1) -> list of strings
336         
337         Return a list of the words in S, using sep as the
338         delimiter string, starting at the end of the string and
339         working to the front.  If maxsplit is given, at most maxsplit
340         splits are done. If sep is not specified, any whitespace string
341         is a separator.
342         """
343         return []
344 
345     def rstrip(self, chars=None): # real signature unknown; restored from __doc__
346         """
347         S.rstrip([chars]) -> str
348         
349         Return a copy of the string S with trailing whitespace removed.
350         If chars is given and not None, remove characters in chars instead.
351         """
352         return ""
353 
354     def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
355         """
356         S.split(sep=None, maxsplit=-1) -> list of strings
357         
358         Return a list of the words in S, using sep as the
359         delimiter string.  If maxsplit is given, at most maxsplit
360         splits are done. If sep is not specified or is None, any
361         whitespace string is a separator and empty strings are
362         removed from the result.
363         """
364         return []
365 
366     def splitlines(self, keepends=None): # real signature unknown; restored from __doc__
367         """
368         S.splitlines([keepends]) -> list of strings
369         
370         Return a list of the lines in S, breaking at line boundaries.
371         Line breaks are not included in the resulting list unless keepends
372         is given and true.
373         """
374         return []
375 
376     def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
377         """
378         S.startswith(prefix[, start[, end]]) -> bool
379         
380         Return True if S starts with the specified prefix, False otherwise.
381         With optional start, test S beginning at that position.
382         With optional end, stop comparing S at that position.
383         prefix can also be a tuple of strings to try.
384         """
385         return False
386 
387     def strip(self, chars=None): # real signature unknown; restored from __doc__
388         """
389         S.strip([chars]) -> str
390         
391         Return a copy of the string S with leading and trailing
392         whitespace removed.
393         If chars is given and not None, remove characters in chars instead.
394         """
395         return ""
396 
397     def swapcase(self): # real signature unknown; restored from __doc__
398         """
399         S.swapcase() -> str
400         
401         Return a copy of S with uppercase characters converted to lowercase
402         and vice versa.
403         """
404         return ""
405 
406     def title(self): # real signature unknown; restored from __doc__
407         """
408         S.title() -> str
409         
410         Return a titlecased version of S, i.e. words start with title case
411         characters, all remaining cased characters have lower case.
412         """
413         return ""
414 
415     def translate(self, table): # real signature unknown; restored from __doc__
416         """
417         S.translate(table) -> str
418         
419         Return a copy of the string S in which each character has been mapped
420         through the given translation table. The table must implement
421         lookup/indexing via __getitem__, for instance a dictionary or list,
422         mapping Unicode ordinals to Unicode ordinals, strings, or None. If
423         this operation raises LookupError, the character is left untouched.
424         Characters mapped to None are deleted.
425         """
426         return ""
427 
428     def upper(self): # real signature unknown; restored from __doc__
429         """
430         S.upper() -> str
431         
432         Return a copy of S converted to uppercase.
433         """
434         return ""
435 
436     def zfill(self, width): # real signature unknown; restored from __doc__
437         """
438         S.zfill(width) -> str
439         
440         Pad a numeric string S with zeros on the left, to fill a field
441         of the specified width. The string S is never truncated.
442         """
443         return ""
444 
445     def __add__(self, *args, **kwargs): # real signature unknown
446         """ Return self+value. """
447         pass
448 
449     def __contains__(self, *args, **kwargs): # real signature unknown
450         """ Return key in self. """
451         pass
452 
453     def __eq__(self, *args, **kwargs): # real signature unknown
454         """ Return self==value. """
455         pass
456 
457     def __format__(self, format_spec): # real signature unknown; restored from __doc__
458         """
459         S.__format__(format_spec) -> str
460         
461         Return a formatted version of S as described by format_spec.
462         """
463         return ""
464 
465     def __getattribute__(self, *args, **kwargs): # real signature unknown
466         """ Return getattr(self, name). """
467         pass
468 
469     def __getitem__(self, *args, **kwargs): # real signature unknown
470         """ Return self[key]. """
471         pass
472 
473     def __getnewargs__(self, *args, **kwargs): # real signature unknown
474         pass
475 
476     def __ge__(self, *args, **kwargs): # real signature unknown
477         """ Return self>=value. """
478         pass
479 
480     def __gt__(self, *args, **kwargs): # real signature unknown
481         """ Return self>value. """
482         pass
483 
484     def __hash__(self, *args, **kwargs): # real signature unknown
485         """ Return hash(self). """
486         pass
487 
488     def __init__(self, value='', encoding=None, errors='strict'): # known special case of str.__init__
489         """
490         str(object='') -> str
491         str(bytes_or_buffer[, encoding[, errors]]) -> str
492         
493         Create a new string object from the given object. If encoding or
494         errors is specified, then the object must expose a data buffer
495         that will be decoded using the given encoding and error handler.
496         Otherwise, returns the result of object.__str__() (if defined)
497         or repr(object).
498         encoding defaults to sys.getdefaultencoding().
499         errors defaults to 'strict'.
500         # (copied from class doc)
501         """
502         pass
503 
504     def __iter__(self, *args, **kwargs): # real signature unknown
505         """ Implement iter(self). """
506         pass
507 
508     def __len__(self, *args, **kwargs): # real signature unknown
509         """ Return len(self). """
510         pass
511 
512     def __le__(self, *args, **kwargs): # real signature unknown
513         """ Return self<=value. """
514         pass
515 
516     def __lt__(self, *args, **kwargs): # real signature unknown
517         """ Return self<value. """
518         pass
519 
520     def __mod__(self, *args, **kwargs): # real signature unknown
521         """ Return self%value. """
522         pass
523 
524     def __mul__(self, *args, **kwargs): # real signature unknown
525         """ Return self*value.n """
526         pass
527 
528     @staticmethod # known case of __new__
529     def __new__(*args, **kwargs): # real signature unknown
530         """ Create and return a new object.  See help(type) for accurate signature. """
531         pass
532 
533     def __ne__(self, *args, **kwargs): # real signature unknown
534         """ Return self!=value. """
535         pass
536 
537     def __repr__(self, *args, **kwargs): # real signature unknown
538         """ Return repr(self). """
539         pass
540 
541     def __rmod__(self, *args, **kwargs): # real signature unknown
542         """ Return value%self. """
543         pass
544 
545     def __rmul__(self, *args, **kwargs): # real signature unknown
546         """ Return self*value. """
547         pass
548 
549     def __sizeof__(self): # real signature unknown; restored from __doc__
550         """ S.__sizeof__() -> size of S in memory, in bytes """
551         pass
552 
553     def __str__(self, *args, **kwargs): # real signature unknown
554         """ Return str(self). """
555         pass
str

查看字符串属性:dir()

 1 a='python'
 2 dir(a)
 3 
 4 #运行后结果
 5 ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getat
 6 tribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__'
 7 , '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setat
 8 tr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', '
 9 expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'isl
10 ower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'pa
11 rtition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith',
12 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
dir

3.部分功能介绍

1)移除空格或字符【strip();lstrip();rstrip()】

strip(self, chars=None)

 删除字符串中开头、结尾处的chars字符,返回一个新字符串,默认参数为空。

lstrip(self, chars=None)

 删除字符串中开头处的chars字符,返回一个新字符串,默认参数为空。

rstrip(self, chars=None)

 删除字符串中结尾处的chars字符,返回一个新字符串,默认参数为空。

 1 s='  python  '
 2 a=s.strip()
 3 b=s.lstrip()
 4 c=s.rstrip()
 5 print(s)
 6 print(a)
 7 print(b)
 8 print(c)
 9 
10 #运行结果
11   python  
12 python
13 python  
14   python
15 
16 s='apythona'
17 a=s.strip('a')
18 b=s.lstrip('a')
19 c=s.rstrip('a')
20 print(s)
21 print(a)
22 print(b)
23 print(c)
24 
25 #运行结果
26 apythona
27 python
28 pythona
29 apython
demo

2) capitalize(self):【首字母变大写】

  把字符串首字母变大写,返回一个新字符串。

1 s='python'
2 a=s.capitalize()
3 print(s)
4 print(a)
5 
6 #运行结果
7 python
8 Python
demo

3)center(self, width, fillchar=None):【字符串内容居中】

  字符串在给定的字符串长度width中内容居中,两边用提供的字符fillchar填充,fillchar默认为空,返回一个新字符串。

 1 s='python'
 2 a=s.center(10)
 3 b=s.center(10,'#')
 4 print(s)
 5 print(a)
 6 print(b)
 7 
 8 #运行结果
 9 python
10    python  
11 ##python##
demo

4)count(self, sub, start=None, end=None): 

在指定位置start与end之间,计算sub字符的数量,start与end默认为None,返回一个int数值。

 1 s= 'hello world'
 2 a=s.count('o')
 3 b=s.count('o',6,11)
 4 c=s.count('o',6,15)
 5 d=s.count('o',5,-4)
 6 f=s.count('o',-5,-3)
 7 print(a)
 8 print(b)
 9 print(c)
10 print(d)
11 print(f)
12 
13 #运行结果
14 2
15 1
16 1
17 0
18 1
demo
5)endswith(self, suffix, start=None, end=None):
判断字符串在start与end位置之间是不是以某个子序列suffix结尾,返回一个布尔值。【startswith()是判断字符串在start与end位置之间是不是以某个子序列suffix开头,用法和endswith相同】
1 name='olive'
2 res=name.endswith('e')
3 res1=name.endswith('e',0,4)
4 print(res)
5 print(res1)
6 
7 #运行结果
8 True
9 False
demo
6)expandtabs(self, tabsize=8):
把字符串中tab字符替换成tabsize-1个字节的空字符,tabsize默认值为8,返回一个新字符串。
 1 s='a\tbc'
 2 res=s.expandtabs()
 3 res1=s.expandtabs(12)
 4 print(s,len(s))
 5 print(res,len(res))
 6 print(res1,len(res1))
 7 
 8 #运行结果
 9 a  bc 4
10 a       bc 10
11 a           bc 14
demo

7)find(self, sub, start=None, end=None):

找字符串在start与end位置间子序列sub最开始出现的位置,start与end默认为None,返回一个int值,字符串不含sub子序列,则返回-1。【rfind()从右找字符串在start与end位置间子序列sub最开始出现的位置,用法和find()相同】

 1 s='aabbbcccc'
 2 res=s.find('b')
 3 res1=s.find('b',3)
 4 res2=s.find('d')
 5 print(res)
 6 print(res1)
 7 print(res2)
 8 
 9 #运行结果
10 2
11 3
12 -1
demo

8)index(self, sub, start=None, end=None):

索引,功能和find()一样,但是当字符串不含sub子序列时,报ValueError错误。【rindex()从右找字符,用法与index()相同】

 1 s='aabbbcccc'
 2 res=s.index('b')
 3 res1=s.index('b',3,)
 4 print(res)
 5 print(res1)
 6 
 7 #运行结果
 8 2
 9 3
10 
11 s='aabbbcccc'
12 res2=s.index('d')
13 print(res2)
14 
15 #运行上面这个结果则为
16 ValueError: substring not found
demo

9)format(self, *args, **kwargs):

返回一个格式化的字符串,使用参数被替换,替换由{}标识。与占位符(%f,%d,%s,%x)格式化功能差不多,下面一起举例。

 1 s='I am {},like {}'            #{}可以写上序号,也可以不写,序号从0开始
 2 s1='I am {name},like {obj}'
 3 s2='I am {1} ,like {0}'      #可以是反序
 4 s3='I am %s,like %s'
 5 res=s.format('olive','lotus')
 6 res1=s1.format(name='olive',obj='lotus')
 7 res2=s2.format('olive','lotus')
 8 res3=s3%('olive','lotus')     #占位符格式化
 9 print(res)
10 print(res1)
11 print(res2)
12 print(res3)
13 
14 #运行结果
15 I am olive,like lotus
16 I am olive,like lotus
17 I am lotus ,like olive
18 I am olive,like lotus
demo

10)join(self, iterable):

连接iterable列表里的字符串,返回字符串。

1 s=['p','y','t','h','o','n']
2 res=''.join(s)
3 res1='*'.join(s)            #''给出连接分隔符
4 print(res)
5 print(res1)
6 
7 运行结果
8 python
9 p*y*t*h*o*n
demo

11)partition(self, sep):

以sep为分隔符,把字符串分割,返回一个元组。【rpartition()从右查找sep,用法与partition()相同】

1 s = 'olivelikelotus'
2 res=s.partition('like')
3 print(res,type(res))
4 
5 #运行结果
6 ('olive', 'like', 'lotus') <class 'tuple'>
demo

12)replace(self, old, new, count=None):

把字符串中某个子序列old替换成一个新序列new,count是替换数,返回一个新字符串。

1 s = 'olivelikelotus'
2 res=s.replace('l','*')
3 res1=s.replace('l','*s',2)
4 print(res)
5 print(res1)
6 
7 #运行结果
8 o*ive*ike*otus
9 o*sive*sikelotus
demo

13)split(self, sep=None, maxsplit=-1):

把字符串以sep为分隔符分割,sep作为分隔符会被删除,maxsplit为分割次数,返回一个列表。【rsplit()是从右找sep,splitlines()是按行分割,用法与都split()相同】

 1 s = 'olivelikelotus'
 2 s1 = 'olive like lotus'
 3 res=s.split()
 4 res1=s.split('l',1)
 5 res2=s1.split()
 6 res3=s1.split(' ',1)
 7 print(res)
 8 print(res1)
 9 print(res2)
10 print(res3)
11 
12 #运行结果
13 ['olivelikelotus']
14 ['o', 'ivelikelotus']
15 ['olive', 'like', 'lotus']
16 ['olive', 'like lotus']
demo

14)字符串切片(slice)

从一个字符串中截取字符串,格式: [start:end:step],start与end是截取起始结束位置,step是截取间隔。

 1 s = 'iamolivelikecherry!'
 2 sed=s[3:-1]
 3 sed2=s[::2]
 4 sed3=s[:-1]
 5 sed4=s[3:]
 6 
 7 print(sed)
 8 print(sed2)
 9 print(sed3)
10 print(sed4)
11 
12 #运行结果
13 olivelikecherry
14 imlvlkcer!
15 iamolivelikecherry
16 olivelikecherry!
demo

15)__add__(self, *args, **kwargs):

在原字符串上加上一个子序列,返回一个字符串。

1 s='abc'
2 res=s.__add__('def')
3 print(res,type(res))
4 
5 #运行结果
6 abcdef <class 'str'>
demo

16)__contains__(self, *args, **kwargs):
判断字符串包不包含给出的参数,返回布尔值。
功能和in相同。

1 name='python'
2 result= name.__contains__('o')
3 result1='ho' in name
4 print(result)
5 print(result1)
6 
7 #运行结果
8 True
9 True
demo
17)__eq__(self, *args, **kwargs):
判断字符串是否与查找的字符串一样,返回布尔值。【__ge__()、__gt__()、__le__()、__lt__()用法和__eq__()相同】
1 s='abc'
2 res=s.__eq__('a')
3 res1=s.__eq__('abc')
4 print(res)
5 print(res1)
6 
7 #运行结果
8 False
9 True
demo