字符串

定义:它是一个有序的字符的集合,用于存储和表示基本的文本信息,‘’或“”或‘’‘ ’‘’中间包含的内容称之为字符串
特性:
1.只能存放一个值
2.不可变,只能重新赋值
3.按照从左到右的顺序定义字符集合,下标从0开始顺序访问,有序

字符串常用功能

移除空白

分割

长度

索引

切片

格式化输出

详细举例,上篇博文有写

字符常用內建函数

  1 def capitalize(self): # real signature unknown; restored from __doc__
  2     """
  3     B.capitalize() -> copy of B
  4     把字符串的第一个字符大写
  5     Return a copy of B with only its first character capitalized (ASCII)
  6     and the rest lower-cased.
  7     """
  8     pass
  9
 10 def center(self, width, fillchar=None): # real signature unknown; restored from __doc__
 11     """
 12     B.center(width[, fillchar]) -> copy of B
 13     返回一个原字符串居中,并使用空格填充至长度width的新字符
 14     Return B centered in a string of length width.  Padding is
 15     done using the specified fill character (default is a space).
 16     """
 17     pass
 18
 19 def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
 20     """
 21     B.count(sub[, start[, end]]) -> int
 22     返回str在string里面出现的次数,如果start或者end指定则返回指定范围内str出现的次数
 23     Return the number of non-overlapping occurrences of subsection sub in
 24     bytes B[start:end].  Optional arguments start and end are interpreted
 25     as in slice notation.
 26     """
 27     return 0
 28
 29 def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__
 30     """
 31     S.encode(encoding='utf-8', errors='strict') -> bytes
 32     以encoding 指定的编码格式解码string,如果出错默认报一个ValueError的异常,除非errors指定的是‘ignore’或者replace
 33     Encode S using the codec registered for encoding. Default encoding
 34     is 'utf-8'. errors may be given to set a different error
 35     handling scheme. Default is 'strict' meaning that encoding errors raise
 36     a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
 37     'xmlcharrefreplace' as well as any other name registered with
 38     codecs.register_error that can handle UnicodeEncodeErrors.
 39     """
 40     pass
 41
 42 def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
 43     """
 44     B.endswith(suffix[, start[, end]]) -> bool
 45     检查字符串是否以suffix结束,如果start或者end指定则检查指定的范围内是否以suffix结束,如果是返回True,否则返回False
 46     Return True if B ends with the specified suffix, False otherwise.
 47     With optional start, test B beginning at that position.
 48     With optional end, stop comparing B at that position.
 49     suffix can also be a tuple of bytes to try.
 50     """
 51     return False
 52
 53 def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__
 54     """
 55     B.expandtabs(tabsize=8) -> copy of B
 56     把字符串string中的tab符号\t转换为空格,默认的空格数tabsize是8
 57     Return a copy of B where all tab characters are expanded using spaces.
 58     If tabsize is not given, a tab size of 8 characters is assumed.
 59     """
 60     pass
 61
 62 def insert(self, *args, **kwargs): # real signature unknown
 63     """
 64     Insert a single item into the bytearray before the given index.
 65
 66       index
 67         The index where the value is to be inserted.
 68       item
 69         The item to be inserted.
 70     """
 71     pass
 72
 73 def isalnum(self): # real signature unknown; restored from __doc__
 74     """
 75     B.isalnum() -> bool
 76     如果string至少有一个字符并且所有字符都是字母或数字则返回True,否则返回False
 77     Return True if all characters in B are alphanumeric
 78     and there is at least one character in B, False otherwise.
 79     """
 80     return False
 81
 82 def isalpha(self): # real signature unknown; restored from __doc__
 83     """
 84     B.isalpha() -> bool
 85     如果string至少有一个字符并且所有字符都是字母则返回True,否则返回False
 86     Return True if all characters in B are alphabetic
 87     and there is at least one character in B, False otherwise.
 88     """
 89     return False
 90
 91 def isdigit(self): # real signature unknown; restored from __doc__
 92     """
 93     B.isdigit() -> bool
 94     如果string只包含十进制数字则返回True,否则返回False
 95     Return True if all characters in B are digits
 96     and there is at least one character in B, False otherwise.
 97     """
 98     return False
 99
100 def islower(self): # real signature unknown; restored from __doc__
101     """
102     B.islower() -> bool
103     如果string中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回True,否则返回False
104     Return True if all cased characters in B are lowercase and there is
105     at least one cased character in B, False otherwise.
106     """
107     return False
108
109 def isspace(self): # real signature unknown; restored from __doc__
110     """
111     B.isspace() -> bool
112     如果string中只包含空格,则返回Ture,否则返回False
113     Return True if all characters in B are whitespace
114     and there is at least one character in B, False otherwise.
115     """
116     return False
117
118 def istitle(self): # real signature unknown; restored from __doc__
119     """
120     B.istitle() -> bool
121     如果string是标题化的(就是首字母大写)则返回True,否则返回False
122     Return True if B is a titlecased string and there is at least one
123     character in B, i.e. uppercase characters may only follow uncased
124     characters and lowercase characters only cased ones. Return False
125     otherwise.
126     """
127     return False
128
129 def isupper(self): # real signature unknown; restored from __doc__
130     """
131     B.isupper() -> bool
132     如果string中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回True,否则返回False
133     Return True if all cased characters in B are uppercase and there is
134     at least one cased character in B, False otherwise.
135     """
136     return False
137
138 def join(self, *args, **kwargs): # real signature unknown
139     """
140     Concatenate any number of bytes/bytearray objects.
141     以string 作为分隔符,将序列中所有的元素(的字符串表示)合并为一个新的字符串
142     The bytearray whose method is called is inserted in between each pair.
143
144     The result is returned as a new bytearray object.
145     """
146     pass
147
148 def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__
149     """
150     B.ljust(width[, fillchar]) -> copy of B
151     返回一个原字符左对齐,并使用空格填充至长度width的新字符串
152     Return B left justified in a string of length width. Padding is
153     done using the specified fill character (default is a space).
154     """
155     pass
156
157 def lower(self): # real signature unknown; restored from __doc__
158     """
159     B.lower() -> copy of B
160     转换sting中所有大写字符为小写
161     Return a copy of B with all ASCII characters converted to lowercase.
162     """
163     pass
164
165 def maketrans(*args, **kwargs): # real signature unknown
166     """
167     Return a translation table useable for the bytes or bytearray translate method.
168
169     The returned table will be one where each byte in frm is mapped to the byte at
170     the same position in to.
171
172     The bytes objects frm and to must be of the same length.
173     """
174     pass
175
176 def partition(self, sep): # real signature unknown; restored from __doc__
177     """
178     S.partition(sep) -> (head, sep, tail)
179     有点像find()和split()的结合体,从str出现的第一个位置起,把字符串string分成一个三字符的元组(string_pre_str,str,
180     string_post_str),如果string中不包含str则string_pre_str == string.
181     Search for the separator sep in S, and return the part before it,
182     the separator itself, and the part after it.  If the separator is not
183     found, return S and two empty strings.
184     """
185     pass
186
187 def pop(self, *args, **kwargs): # real signature unknown
188     """
189     Remove and return a single item from B.
190
191       index
192         The index from where to remove the item.
193         -1 (the default value) means remove the last item.
194
195     If no index argument is given, will pop the last item.
196     """
197     pass
198
199 def remove(self, *args, **kwargs): # real signature unknown
200     """
201     Remove the first occurrence of a value in the bytearray.
202
203       value
204         The value to remove.
205     """
206     pass
207
208 def replace(self, old, new, count=None):  # real signature unknown; restored from __doc__
209     """
210     S.replace(old, new[, count]) -> str
211     把string中的old替换成new,如果count指定,则替换不超过count次
212     Return a copy of S with all occurrences of substring
213     old replaced by new.  If the optional argument count is
214     given, only the first count occurrences are replaced.
215     """
216     return ""
217 def reverse(self, *args, **kwargs): # real signature unknown
218     """ Reverse the order of the values in B in place. """
219     pass
220
221 def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
222     """
223     B.find(sub[, start[, end]]) -> int
224     检测str是否包含在string中,如果start和end指定范围,则检查是否包含在指定范围内,如果是返回开始的索引值,否则返回-1
225     Return the lowest index in B where subsection sub is found,
226     such that sub is contained within B[start,end].  Optional
227     arguments start and end are interpreted as in slice notation.
228
229     Return -1 on failure.
230     """
231     return 0
232
233 def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
234     """
235     B.rfind(sub[, start[, end]]) -> int
236     类似于find()函数,不过是从右边开始查找
237     Return the highest index in B where subsection sub is found,
238     such that sub is contained within B[start,end].  Optional
239     arguments start and end are interpreted as in slice notation.
240
241     Return -1 on failure.
242     """
243     return 0
244
245 def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
246     """
247     B.index(sub[, start[, end]]) -> int
248     跟find()方法一样,只不过如果str不在string中会报一个异常
249     Like B.find() but raise ValueError when the subsection is not found.
250     """
251     return 0
252
253 def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
254     """
255     B.rindex(sub[, start[, end]]) -> int
256     类似于index(),不过是从右边开始
257     Like B.rfind() but raise ValueError when the subsection is not found.
258     """
259     return 0
260
261 def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__
262     """
263     B.rjust(width[, fillchar]) -> copy of B
264     返回一个原字符串右对齐,并使用空格填充至长度width的新字符串
265     Return B right justified in a string of length width. Padding is
266     done using the specified fill character (default is a space)
267     """
268     pass
269
270 def rpartition(self, sep): # real signature unknown; restored from __doc__
271     """
272     S.rpartition(sep) -> (head, sep, tail)
273     类似于partition()函数,不过是从右边开始查找
274     Search for the separator sep in S, starting at the end of S, and return
275     the part before it, the separator itself, and the part after it.  If the
276     separator is not found, return two empty strings and S.
277     """
278     pass
279
280 def strip(self, chars=None):  # real signature unknown; restored from __doc__
281     """
282     S.strip([chars]) -> str
283     删除string字符串左右两边的空格、\n回车
284     Return a copy of the string S with leading and trailing
285     whitespace removed.
286     If chars is given and not None, remove characters in chars instead.
287     """
288     return ""
289
290 def rstrip(self, *args, **kwargs): # real signature unknown
291     """
292     Strip trailing bytes contained in the argument.
293     删除string字符串末尾的空格
294     If the argument is omitted or None, strip trailing ASCII whitespace.
295     """
296     pass
297
298 def lstrip(self, chars=None):  # real signature unknown; restored from __doc__
299     """
300     S.lstrip([chars]) -> str
301     截掉string左边的空格
302     Return a copy of the string S with leading whitespace removed.
303     If chars is given and not None, remove characters in chars instead.
304     """
305     return ""
306
307 def split(self, sep=None, maxsplit=-1):  # real signature unknown; restored from __doc__
308     """
309     S.split(sep=None, maxsplit=-1) -> list of strings
310     以seq为分隔符切片string,与partition的区别结果不包含seq,如果maxsplit有指定值,仅分割maxsplit个字符串
311     Return a list of the words in S, using sep as the
312     delimiter string.  If maxsplit is given, at most maxsplit
313     splits are done. If sep is not specified or is None, any
314     whitespace string is a separator and empty strings are
315     removed from the result.
316     """
317     return []
318
319 def rsplit(self, sep=None, maxsplit=-1):  # real signature unknown; restored from __doc__
320     """
321     S.rsplit(sep=None, maxsplit=-1) -> list of strings
322
323     Return a list of the words in S, using sep as the
324     delimiter string, starting at the end of the string and
325     working to the front.  If maxsplit is given, at most maxsplit
326     splits are done. If sep is not specified, any whitespace string
327     is a separator.
328     """
329     return []
330
331 def splitlines(self, keepends=None):  # real signature unknown; restored from __doc__
332     """
333     S.splitlines([keepends]) -> list of strings
334     按照行分隔,返回一个包含各行作为元素的列表
335     Return a list of the lines in S, breaking at line boundaries.
336     Line breaks are not included in the resulting list unless keepends
337     is given and true.
338     """
339     return []
340
341 def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
342     """
343     B.startswith(prefix[, start[, end]]) -> bool
344     检查字符串是否是以prefix开头,是则返回True,否则返回False。如果start和end指定值,则在指定范围内检查
345     Return True if B starts with the specified prefix, False otherwise.
346     With optional start, test B beginning at that position.
347     With optional end, stop comparing B at that position.
348     prefix can also be a tuple of bytes to try.
349     """
350     return False
351
352 def swapcase(self): # real signature unknown; restored from __doc__
353     """
354     B.swapcase() -> copy of B
355     翻转string中大小写
356     Return a copy of B with uppercase ASCII characters converted
357     to lowercase ASCII and vice versa.
358     """
359     pass
360
361 def title(self):  # real signature unknown; restored from __doc__
362     """
363     S.title() -> str
364     返回“标题化”的string,就是说所有单词都是以大写开始,其余字母均为小写
365     Return a titlecased version of S, i.e. words start with title case
366     characters, all remaining cased characters have lower case.
367     """
368     return ""
369
370 def translate(self, table, deletechars=None): # real signature unknown; restored from __doc__
371     """
372     translate(table, [deletechars])
373     根据table的表(包含256个字符)转换string的字符,要过滤掉的字符放到deletechars参数中
374     Return a copy with each character mapped by the given translation table.
375
376       table
377         Translation table, which must be a bytes object of length 256.
378
379     All characters occurring in the optional argument deletechars are removed.
380     The remaining characters are mapped through the given translation table.
381     """
382     pass
383
384 def upper(self): # real signature unknown; restored from __doc__
385     """
386     B.upper() -> copy of B
387     转换string中的小写字母为大写
388     Return a copy of B with all ASCII characters converted to uppercase.
389     """
390     pass
391
392 def zfill(self, width): # real signature unknown; restored from __doc__
393     """
394     B.zfill(width) -> copy of B
395     返回长度为width的字符串,原字符串string右对齐,前面填充0
396     Pad a numeric string B with zeros on the left, to fill a field
397     of the specified width.  B is never truncated.
398     """
399     pass
400
401 def format(self, *args, **kwargs):  # known special case of str.format
402     """
403     S.format(*args, **kwargs) -> str
404
405     Return a formatted version of S, using substitutions from args and kwargs.
406     The substitutions are identified by braces ('{' and '}').
407     """
408     pass
409
410 def format_map(self, mapping):  # real signature unknown; restored from __doc__
411     """
412     S.format_map(mapping) -> str
413
414     Return a formatted version of S, using substitutions from mapping.
415     The substitutions are identified by braces ('{' and '}').
416     """
417     return ""
418
419 def isidentifier(self):  # real signature unknown; restored from __doc__
420     """
421     S.isidentifier() -> bool
422
423     Return True if S is a valid identifier according
424     to the language definition.
425
426     Use keyword.iskeyword() to test for reserved identifiers
427     such as "def" and "class".
428     """
429     return False

View Code

內建函数使用方法

 1 >>> name = "wangeq"
 2 >>> name.capitalize()    #首字母大写
 3 'Wangeq'
 4 >>> name.center(50,'-')   #返回原字符串居中
 5 '----------------------wangeq----------------------'
 6 >>> len(name.center(50,'-'))
 7 50
 8 >>> hello ="welcome to beijing"
 9 >>> hello.count('i')     #计数i在string出现的次数
10 2
11 >>> hello.encode()     #将字符串编码成bytes格式
12 b'welcome to beijing'
13 >>> hello.endswith("ing")  # 判断字符串是否以 ing结尾
14 True
15 >>> hello.endswith("wl")
16 False
17 >>> 'wang\teq'.expandtabs()  #输出'wang    eq', 将\t转换成多长的空格
18 'wang    eq'
19 >>> hello.find('W')   #查找W,找到返回其索引, 找不到返回-1
20 -1
21 >>> hello.find('w')
22 0
23 >>>
24 >>> 'wang12'.isalnum()   #所有字符是否是字母或数字
25 True
26 >>> 'wang12#'.isalnum()
27 False
28 >>> 'wang12'.isalpha()    #所有字符是否都是字母
29 False
30 >>> 'wang'.isalpha()
31 True
32 >>> '12345'.isdigit()     #是否只包含十进制数字
33 True
34 >>> '0x122'.isdigit()
35 False
36 >>> '  '.isspace()     #字符是否只包含空格
37 True
38 >>> 'Welcome To Beijing'.istitle()  #是否标题化,首字母大写
39 True
40 >>> '|'.join(['wangeq','jack','rose']) #以 ‘|’ 作为分隔符,将序列中字符合并为一个字符
41 'wangeq|jack|rose'
42 >>> hello.ljust(50,"-")       #左对齐字符串,指定50个字符,以“-”填充空格
43 'welcome to beijing--------------------------------'
44 >>> hello.rjust(50,"-")      #右对齐
45 '--------------------------------welcome to beijing'
46 >>> "WANGeq".lower()     #转换为小写
47 'wangeq'
48 >>> 'welcome to beijing'.replace('to','TO')  #TO替换to
49 'welcome TO beijing'
50 >>> 'welcome to beijing'.index('i')   #查找‘c’ 下标位置,从左开始
51 13
52 >>> 'welcome to beijing'.rindex('i')   #查找‘c’ 下标位置,从右开始
53 15
54 >>> '   wang  \n'.strip()   #去掉字符串左右空格
55 'wang'
56 >>> '   wang  \n'.rstrip()
57 '   wang'
58 >>> '   wang  \n'.lstrip()
59 'wang  \n'
60 >>> 'WangisDDD'.swapcase()  #翻转大小写字母
61 'wANGISddd'
62 >>> 'WNSNsssd ddd'.upper()   #翻转字符串中小写为大写
63 'WNSNSSSD DDD'
64 >>> 'wangeq'.zfill(50)            #返回长度为50字符串右对齐,前面填充0
65 '00000000000000000000000000000000000000000000wangeq'
66 format:
67 >>> msg = "my name is {},and age is {}"
68 >>> msg.format("wange",23)
69 'my name is wange,and age is 23'
70 >>> msg = "my name is {0},and age is {1}"
71 >>> msg.format("wange",24)
72 'my name is wangeq,and age is 24'
73 >>> msg = "my name is {name},and age is {age}"
74 >>> msg.format(age=23,name="wange")
75 'my name is wange,and age is 23'
76 format_map:
77 >>> msg = "my name is {name},and age is {age}"
78 >>> msg.format_map({'name':'wangeq','age':22})
79 'my name is wangeq,and age is 22'
80 maketrans:
81 >>> intab = 'abcdef'
82 >>> outtab = '123456'
83 >>> trantab = str.maketrans(intab, outtab)
84 >>> str = "this is string example...."
85 >>> str.translate(trantab)
86 'this is string 5x1mpl5....'
87 >>>
88 >>> c = "wangeq_ssdd"   #检测一段字符串可否被当作标志符,即是否符合变量命名规则
89 >>> c.isidentifier()
90 True

转载于:https://www.cnblogs.com/wangeq/p/6289639.html

python基础(二)字符串內建函数详解相关推荐

  1. Python基础之格式化输出函数format()功能详解

    之前发过一篇文章:Python基础之常用格式化输出字符详解 但是呢,有时候我们需要用到多个%的时候,用这个就很不方便了,比如数错%数量或者一 一对应的时候... 这里补充一个字典方式的格式化输出字符的 ...

  2. python3 format函数_Python学习教程:Python3之字符串格式化format函数详解(上)

    Python学习教程:Python3之字符串格式化format函数详解(上) 概述 在Python3中,字符串格式化操作通过format()方法或者f'string'实现.而相比于老版的字符串格式化方 ...

  3. format函数_Python学习教程:Python3之字符串格式化format函数详解(上)

    Python学习教程:Python3之字符串格式化format函数详解(上) 概述 在Python3中,字符串格式化操作通过format()方法或者f'string'实现.而相比于老版的字符串格式化方 ...

  4. python中zip的使用_浅谈Python中的zip()与*zip()函数详解

    前言 1.实验环境: Python 3.6: 2.示例代码地址:下载示例: 3.本文中元素是指列表.元组.字典等集合类数据类型中的下一级项目(可能是单个元素或嵌套列表). zip(*iterables ...

  5. Python+NetworkX画图的nx.draw_networkx(函数详解)

    Python+NetworkX画图的nx.draw_networkx函数详解 Python+NetworkX画图的nx.draw_networkx(函数详解) Python+NetworkX画图的nx ...

  6. python中argparse模块关于 parse_args() 函数详解(全)

    目录 前言 1. 函数讲解 2. 基本用法 3. 实战讲解 前言 原理:命令行解析使用argparse包 作用:命令行传参赋值 可用在机器学习深度学习 或者 脚本运行等 了解这个函数需要了解其背后的原 ...

  7. python基础:字符串的join()函数使用

    python 字符串的join()函数,支持字符串的特殊拼接,用于将序列中的元素与指定的字符或者字符串连接生成一个新的字符串. join()的使用语法为: str.join(sequence) seq ...

  8. 【Python基础教程】变量的作用域详解

    变量作用域 Python 能够改变变量作用域的代码段是 def . class . lamda. if/elif/else.try/except/finally.for/while 并不能涉及变量作用 ...

  9. python基础教程笔记—即时标记(详解)

    最近一直在学习python,语法部分差不多看完了,想写一写python基础教程后面的第一个项目.因为我在网上看到的别人的博客讲解都并不是特别详细,仅仅是贴一下代码,书上内容照搬一下,对于当时刚学习py ...

最新文章

  1. Android之记录并研究Volley框架中知识点
  2. Android查询数据库问题
  3. 在细分场景的时代,如何反欺诈和防止内外勾结?
  4. boost::ratio_multiply相关的测试程序
  5. PyTorch | 通过torch.eye创建单位对角矩阵 | torch.eye()如何使用?torch.eye()例子 | torch.eye()使用方法
  6. vue实现部分页面导入底部 vue配置公用头部、底部,可控制显示隐藏
  7. java中sort函数comparator的使用_Java Comparator comparingInt()用法及代码示例
  8. Mybatis generator创建项目核心文件
  9. 2003下使用IIS+PHP+MySQL来运行DZ(落伍记号)
  10. 在二维码中间添加logo或者图片
  11. loongson2f_龙芯灵珑9S2A一体机tftp+usb安装debian6 详细过程:
  12. Apache ShenYu网关初体验
  13. 极速办公(Excel)如何方框内打勾
  14. 计算机桌面图标有小锁如何去掉,去掉电脑桌面图标小黄锁的两种方法
  15. 跑步时戴什么耳机好、分享五款最适合跑步的运动耳机排名清单
  16. 饿了么table排序
  17. 龙芯平台上的容器和CI/CD实现方案
  18. 深航App劫持微信;Apple News上线首日遭遇各种崩溃;华为P30“望远镜手机”正式发布 | 雷锋早报... 1
  19. 服务器显示idc,知道一个IP,怎么查询这个服务器是哪家IDC提供的?
  20. 放不下的原理_想要彻底忘记一个人,明白“洛克定律”的真实原理就可以

热门文章

  1. Java并发编程实战 第13章 显式锁
  2. 【转载】ogre内存管理
  3. Docker shipyard 试用
  4. NHibernate 学习总结 开篇
  5. cgic: 为C语言编写CGI的C函数库
  6. 计算机硬盘read,为你解答电脑开机提示a disk read error occurred怎么办
  7. java 雪花特效_java实现图片飘雪花的特效
  8. pytorch安装换源ubuntu_ubuntu 安装pytorch问题
  9. Android Native crash 处理案例分享
  10. 神马搜索如何提升搜索的时效性?