本节内容

一、字符串

记住:

  1. 有序类型:列表,元组,字符串 ---> 都可迭代; 无序类型:字典,集合 ---> 不可迭代;

特性:不可修改

  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.  
  15. def capitalize(self): # real signature unknown; restored from __doc__
  16. """
  17. 首字母变大写
  18. S.capitalize() -> str
  19.  
  20. Return a capitalized version of S, i.e. make the first character
  21. have upper case and the rest lower case.
  22. """
  23. return ""
  24.  
  25. def casefold(self): # real signature unknown; restored from __doc__
  26. """
  27. 把整个字符串的所有字符改为小写
  28. S.casefold() -> str
  29.  
  30. Return a version of S suitable for caseless comparisons.
  31. """
  32. return ""
  33.  
  34. def center(self, width, fillchar=None): # real signature unknown; restored from __doc__
  35. """
  36. 原来空格居中,不够用空格补全
  37. S.center(width[, fillchar]) -> str
  38.  
  39. Return S centered in a string of length width. Padding is
  40. done using the specified fill character (default is a space)
  41. """
  42. return ""
  43.  
  44. def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
  45. """
  46. 从一个范围内的统计某 str 出现次数
  47. S.count(sub[, start[, end]]) -> int
  48.  
  49. Return the number of non-overlapping occurrences of substring sub in
  50. string S[start:end]. Optional arguments start and end are
  51. interpreted as in slice notation.
  52. """
  53. return 0
  54.  
  55. def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__
  56. """
  57. 以encoding指定的编码格式对字符串编码,如果出错默认报一个ValueError,
  58. 除非errors指定的是 ignore 或 replace
  59. S.encode(encoding='utf-8', errors='strict') -> bytes
  60.  
  61. Encode S using the codec registered for encoding. Default encoding
  62. is 'utf-8'. errors may be given to set a different error
  63. handling scheme. Default is 'strict' meaning that encoding errors raise
  64. a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
  65. 'xmlcharrefreplace' as well as any other name registered with
  66. codecs.register_error that can handle UnicodeEncodeErrors.
  67. """
  68. return b""
  69.  
  70. def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
  71. """
  72. 检查字符串是否以 suffix 子字符串结束,start和end 表示范围,可选
  73. S.endswith(suffix[, start[, end]]) -> bool
  74.  
  75. Return True if S ends with the specified suffix, False otherwise.
  76. With optional start, test S beginning at that position.
  77. With optional end, stop comparing S at that position.
  78. suffix can also be a tuple of strings to try.
  79. """
  80. return False
  81.  
  82. def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__
  83. """
  84. 将字符串中包含的 \t 转换成tabsize个空格
  85. S.expandtabs(tabsize=8) -> str
  86.  
  87. Return a copy of S where all tab characters are expanded using spaces.
  88. If tabsize is not given, a tab size of 8 characters is assumed.
  89. """
  90. return ""
  91.  
  92. def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
  93. """
  94. 检查sub是否包含在字符串中,如果有 返回索引值,否则返回-1
  95. S.find(sub[, start[, end]]) -> int
  96.  
  97. Return the lowest index in S where substring sub is found,
  98. such that sub is contained within S[start:end]. Optional
  99. arguments start and end are interpreted as in slice notation.
  100.  
  101. Return -1 on failure.
  102. """
  103. return 0
  104.  
  105. def format(self, *args, **kwargs): # known special case of str.format
  106. """
  107. 格式化输出
  108. 三种形式:
  109. 形式一:
  110. >>>print('{0}{1}{0}'.format('a','b'))
  111. aba
  112.  
  113. 形式二:(必须一一对应)
  114. >>>print('{}{}{}'.format('a','b'))
  115. Traceback (most recent call last):
  116. File "<input>", line 1, in <module>
  117. IndexError: tuple index out of range
  118. >>>print('{}{}'.format('a','b'))
  119. ab
  120.  
  121. 形式三:
  122. >>>print('{name} {age}'.format(age=18,name='hyp'))
  123. hyp 18
  124.  
  125. S.format(*args, **kwargs) -> str
  126.  
  127. Return a formatted version of S, using substitutions from args and kwargs.
  128. The substitutions are identified by braces ('{' and '}').
  129. """
  130. pass
  131.  
  132. def format_map(self, mapping): # real signature unknown; restored from __doc__
  133. """
  134. 与 format 区别
  135. '{name}'.format(**dict(name='hyp'))
  136. '{name}'.format_map(dict(name='hyp'))
  137.  
  138. S.format_map(mapping) -> str
  139.  
  140. Return a formatted version of S, using substitutions from mapping.
  141. The substitutions are identified by braces ('{' and '}').
  142. """
  143. return ""
  144.  
  145. def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
  146. """
  147. 跟find一样,当索引值不存在时,会产生一个异常
  148. S.index(sub[, start[, end]]) -> int
  149.  
  150. Return the lowest index in S where substring sub is found,
  151. such that sub is contained within S[start:end]. Optional
  152. arguments start and end are interpreted as in slice notation.
  153.  
  154. Raises ValueError when the substring is not found.
  155. """
  156. return 0
  157.  
  158. def isalnum(self): # real signature unknown; restored from __doc__
  159. """
  160. 至少一个字符,且都是字母或数字才返回True
  161. S.isalnum() -> bool
  162.  
  163. Return True if all characters in S are alphanumeric
  164. and there is at least one character in S, False otherwise.
  165. """
  166. return False
  167.  
  168. def isalpha(self): # real signature unknown; restored from __doc__
  169. """
  170. 至少一个字符,且都是字母才返回True
  171. S.isalpha() -> bool
  172.  
  173. Return True if all characters in S are alphabetic
  174. and there is at least one character in S, False otherwise.
  175. """
  176. return False
  177.  
  178. def isdecimal(self): # real signature unknown; restored from __doc__
  179. """
  180. 字符串只包含十进制数字 则返回True
  181. S.isdecimal() -> bool
  182.  
  183. Return True if there are only decimal characters in S,
  184. False otherwise.
  185. """
  186. return False
  187.  
  188. def isdigit(self): # real signature unknown; restored from __doc__
  189. """
  190. 字符串只包含数字 则返回True
  191. S.isdigit() -> bool
  192.  
  193. Return True if all characters in S are digits
  194. and there is at least one character in S, False otherwise.
  195. """
  196. return False
  197.  
  198. def isidentifier(self): # real signature unknown; restored from __doc__
  199. """
  200. 字符串为关键字 则返回True
  201. S.isidentifier() -> bool
  202.  
  203. Return True if S is a valid identifier according
  204. to the language definition.
  205.  
  206. Use keyword.iskeyword() to test for reserved identifiers
  207. such as "def" and "class".
  208. """
  209. return False
  210.  
  211. def islower(self): # real signature unknown; restored from __doc__
  212. """
  213. 字符串中至少包含一个区分大小写的字符,并且字符都是小写,则返回True,否则False
  214. S.islower() -> bool
  215.  
  216. Return True if all cased characters in S are lowercase and there is
  217. at least one cased character in S, False otherwise.
  218. """
  219. return False
  220.  
  221. def isnumeric(self): # real signature unknown; restored from __doc__
  222. """
  223. 字符串只包含数字字符,则返回True
  224. S.isnumeric() -> bool
  225.  
  226. Return True if there are only numeric characters in S,
  227. False otherwise.
  228. """
  229. return False
  230.  
  231. def isprintable(self): # real signature unknown; restored from __doc__
  232. """
  233. S.isprintable() -> bool
  234.  
  235. Return True if all characters in S are considered
  236. printable in repr() or S is empty, False otherwise.
  237. """
  238. return False
  239.  
  240. def isspace(self): # real signature unknown; restored from __doc__
  241. """
  242. 字符串只包含空格,则返回True
  243. S.isspace() -> bool
  244.  
  245. Return True if all characters in S are whitespace
  246. and there is at least one character in S, False otherwise.
  247. """
  248. return False
  249.  
  250. def istitle(self): # real signature unknown; restored from __doc__
  251. """
  252. 字符串是标题化(所有单词都以大写开头,其余字母小写),则返回True
  253. S.istitle() -> bool
  254.  
  255. Return True if S is a titlecased string and there is at least one
  256. character in S, i.e. upper- and titlecase characters may only
  257. follow uncased characters and lowercase characters only cased ones.
  258. Return False otherwise.
  259. """
  260. return False
  261.  
  262. def isupper(self): # real signature unknown; restored from __doc__
  263. """
  264. 字符串中至少包含一个区分大小写的字符,并且字符都是大写,则返回True,否则False
  265. S.isupper() -> bool
  266.  
  267. Return True if all cased characters in S are uppercase and there is
  268. at least one cased character in S, False otherwise.
  269. """
  270. return False
  271.  
  272. def join(self, iterable): # real signature unknown; restored from __doc__
  273. """
  274. 以字符串作为分隔符,插入到sub中所有的字符之间
  275. S.join(iterable) -> str
  276.  
  277. Return a string which is the concatenation of the strings in the
  278. iterable. The separator between elements is S.
  279. """
  280. return ""
  281.  
  282. def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__
  283. """
  284. 返回一个左对齐的字符串,并使空格填充至长度为width的新字符串
  285. S.ljust(width[, fillchar]) -> str
  286.  
  287. Return S left-justified in a Unicode string of length width. Padding is
  288. done using the specified fill character (default is a space).
  289. """
  290. return ""
  291.  
  292. def lower(self): # real signature unknown; restored from __doc__
  293. """
  294. 转换字符串中所有大写字符为小写
  295. S.lower() -> str
  296.  
  297. Return a copy of the string S converted to lowercase.
  298. """
  299. return ""
  300.  
  301. def lstrip(self, chars=None): # real signature unknown; restored from __doc__
  302. """
  303. 去掉字符串左边的所有空格
  304. S.lstrip([chars]) -> str
  305.  
  306. Return a copy of the string S with leading whitespace removed.
  307. If chars is given and not None, remove characters in chars instead.
  308. """
  309. return ""
  310.  
  311. def maketrans(self, *args, **kwargs): # real signature unknown
  312. """
  313. Return a translation table usable for str.translate().
  314.  
  315. If there is only one argument, it must be a dictionary mapping Unicode
  316. ordinals (integers) or characters to Unicode ordinals, strings or None.
  317. Character keys will be then converted to ordinals.
  318. If there are two arguments, they must be strings of equal length, and
  319. in the resulting dictionary, each character in x will be mapped to the
  320. character at the same position in y. If there is a third argument, it
  321. must be a string, whose characters will be mapped to None in the result.
  322. """
  323. pass
  324.  
  325. def partition(self, sep): # real signature unknown; restored from __doc__
  326. """
  327. 找到字符串,把字符串分成一个3元组,如果子字符串不存在,则返回('原字符串','','')
  328. S.partition(sep) -> (head, sep, tail)
  329.  
  330. Search for the separator sep in S, and return the part before it,
  331. the separator itself, and the part after it. If the separator is not
  332. found, return S and two empty strings.
  333. """
  334. pass
  335.  
  336. def replace(self, old, new, count=None): # real signature unknown; restored from __doc__
  337. """
  338. 把字符串中的old子字符串替换成new子字符串,
  339. 如果count指定,则替换不超过count次。
  340. S.replace(old, new[, count]) -> str
  341.  
  342. Return a copy of S with all occurrences of substring
  343. old replaced by new. If the optional argument count is
  344. given, only the first count occurrences are replaced.
  345. """
  346. return ""
  347.  
  348. def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
  349. """
  350. 从右边开始查找,与find类似
  351. S.rfind(sub[, start[, end]]) -> int
  352.  
  353. Return the highest index in S where substring sub is found,
  354. such that sub is contained within S[start:end]. Optional
  355. arguments start and end are interpreted as in slice notation.
  356.  
  357. Return -1 on failure.
  358. """
  359. return 0
  360.  
  361. def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
  362. """"
  363. 从右边开始查找,与index类似
  364. S.rindex(sub[, start[, end]]) -> int
  365.  
  366. Return the highest index in S where substring sub is found,
  367. such that sub is contained within S[start:end]. Optional
  368. arguments start and end are interpreted as in slice notation.
  369.  
  370. Raises ValueError when the substring is not found.
  371. """
  372. return 0
  373.  
  374. def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__
  375. """
  376. S.rjust(width[, fillchar]) -> str
  377.  
  378. Return S right-justified in a string of length width. Padding is
  379. done using the specified fill character (default is a space).
  380. """
  381. return ""
  382.  
  383. def rpartition(self, sep): # real signature unknown; restored from __doc__
  384. """
  385. partition()方法类似
  386. S.rpartition(sep) -> (head, sep, tail)
  387.  
  388. Search for the separator sep in S, starting at the end of S, and return
  389. the part before it, the separator itself, and the part after it. If the
  390. separator is not found, return two empty strings and S.
  391. """
  392. pass
  393.  
  394. def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
  395. """
  396. S.rsplit(sep=None, maxsplit=-1) -> list of strings
  397.  
  398. Return a list of the words in S, using sep as the
  399. delimiter string, starting at the end of the string and
  400. working to the front. If maxsplit is given, at most maxsplit
  401. splits are done. If sep is not specified, any whitespace string
  402. is a separator.
  403. """
  404. return []
  405.  
  406. def rstrip(self, chars=None): # real signature unknown; restored from __doc__
  407. """
  408. 删除字符串末尾的空格
  409. S.rstrip([chars]) -> str
  410.  
  411. Return a copy of the string S with trailing whitespace removed.
  412. If chars is given and not None, remove characters in chars instead.
  413. """
  414. return ""
  415.  
  416. def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
  417. """
  418. 不带参数默认是以空格为分隔符切片字符串,
  419. 如果 maxsplit 参数有设置,则仅分隔 maxsplit 个字符串,返回切片后的子字符串拼接的列表
  420. S.split(sep=None, maxsplit=-1) -> list of strings
  421.  
  422. Return a list of the words in S, using sep as the
  423. delimiter string. If maxsplit is given, at most maxsplit
  424. splits are done. If sep is not specified or is None, any
  425. whitespace string is a separator and empty strings are
  426. removed from the result.
  427. """
  428. return []
  429.  
  430. def splitlines(self, keepends=None): # real signature unknown; restored from __doc__
  431. """
  432. 按照'\n'分隔,返回一个包含隔行作为元素的列表,
  433. 如果 keepends 参数指定,则返回前 keepends
  434. S.splitlines([keepends]) -> list of strings
  435.  
  436. Return a list of the lines in S, breaking at line boundaries.
  437. Line breaks are not included in the resulting list unless keepends
  438. is given and true.
  439. """
  440. return []
  441.  
  442. def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
  443. """
  444. 检查字符串是否以 prefix 开头,是则返回True
  445. start end 可以指定检查范围
  446. S.startswith(prefix[, start[, end]]) -> bool
  447.  
  448. Return True if S starts with the specified prefix, False otherwise.
  449. With optional start, test S beginning at that position.
  450. With optional end, stop comparing S at that position.
  451. prefix can also be a tuple of strings to try.
  452. """
  453. return False
  454.  
  455. def strip(self, chars=None): # real signature unknown; restored from __doc__
  456. """
  457. 删除字符串前边和或变得所有空格,
  458. S.strip([chars]) -> str
  459.  
  460. Return a copy of the string S with leading and trailing
  461. whitespace removed.
  462. If chars is given and not None, remove characters in chars instead.
  463. """
  464. return ""
  465.  
  466. def swapcase(self): # real signature unknown; restored from __doc__
  467. """
  468. 翻转字符串中的大小写
  469. S.swapcase() -> str
  470.  
  471. Return a copy of S with uppercase characters converted to lowercase
  472. and vice versa.
  473. """
  474. return ""
  475.  
  476. def title(self): # real signature unknown; restored from __doc__
  477. """
  478. 返回标题化的字符串
  479. S.title() -> str
  480.  
  481. Return a titlecased version of S, i.e. words start with title case
  482. characters, all remaining cased characters have lower case.
  483. """
  484. return ""
  485.  
  486. def translate(self, table): # real signature unknown; restored from __doc__
  487. """
  488. S.translate(table) -> str
  489.  
  490. Return a copy of the string S in which each character has been mapped
  491. through the given translation table. The table must implement
  492. lookup/indexing via __getitem__, for instance a dictionary or list,
  493. mapping Unicode ordinals to Unicode ordinals, strings, or None. If
  494. this operation raises LookupError, the character is left untouched.
  495. Characters mapped to None are deleted.
  496. """
  497. return ""
  498.  
  499. def upper(self): # real signature unknown; restored from __doc__
  500. """
  501. 转字符串中所有小写字符为大写
  502. S.upper() -> str
  503.  
  504. Return a copy of S converted to uppercase.
  505. """
  506. return ""
  507.  
  508. def zfill(self, width): # real signature unknown; restored from __doc__
  509. """
  510. 返回长度为width的字符串,原字符串右对齐,前面用0填充
  511. S.zfill(width) -> str
  512.  
  513. Pad a numeric string S with zeros on the left, to fill a field
  514. of the specified width. The string S is never truncated.
  515. """
  516. return ""
  517.  
  518. def __add__(self, *args, **kwargs): # real signature unknown
  519. """ Return self+value. """
  520. pass
  521.  
  522. def __contains__(self, *args, **kwargs): # real signature unknown
  523. """ Return key in self. """
  524. pass
  525.  
  526. def __eq__(self, *args, **kwargs): # real signature unknown
  527. """ Return self==value. """
  528. pass
  529.  
  530. def __format__(self, format_spec): # real signature unknown; restored from __doc__
  531. """
  532. S.__format__(format_spec) -> str
  533.  
  534. Return a formatted version of S as described by format_spec.
  535. """
  536. return ""
  537.  
  538. def __getattribute__(self, *args, **kwargs): # real signature unknown
  539. """ Return getattr(self, name). """
  540. pass
  541.  
  542. def __getitem__(self, *args, **kwargs): # real signature unknown
  543. """ Return self[key]. """
  544. pass
  545.  
  546. def __getnewargs__(self, *args, **kwargs): # real signature unknown
  547. pass
  548.  
  549. def __ge__(self, *args, **kwargs): # real signature unknown
  550. """ Return self>=value. """
  551. pass
  552.  
  553. def __gt__(self, *args, **kwargs): # real signature unknown
  554. """ Return self>value. """
  555. pass
  556.  
  557. def __hash__(self, *args, **kwargs): # real signature unknown
  558. """ Return hash(self). """
  559. pass
  560.  
  561. def __init__(self, value='', encoding=None, errors='strict'): # known special case of str.__init__
  562. """
  563. str(object='') -> str
  564. str(bytes_or_buffer[, encoding[, errors]]) -> str
  565.  
  566. Create a new string object from the given object. If encoding or
  567. errors is specified, then the object must expose a data buffer
  568. that will be decoded using the given encoding and error handler.
  569. Otherwise, returns the result of object.__str__() (if defined)
  570. or repr(object).
  571. encoding defaults to sys.getdefaultencoding().
  572. errors defaults to 'strict'.
  573. # (copied from class doc)
  574. """
  575. pass
  576.  
  577. def __iter__(self, *args, **kwargs): # real signature unknown
  578. """ Implement iter(self). """
  579. pass
  580.  
  581. def __len__(self, *args, **kwargs): # real signature unknown
  582. """ Return len(self). """
  583. pass
  584.  
  585. def __le__(self, *args, **kwargs): # real signature unknown
  586. """ Return self<=value. """
  587. pass
  588.  
  589. def __lt__(self, *args, **kwargs): # real signature unknown
  590. """ Return self<value. """
  591. pass
  592.  
  593. def __mod__(self, *args, **kwargs): # real signature unknown
  594. """ Return self%value. """
  595. pass
  596.  
  597. def __mul__(self, *args, **kwargs): # real signature unknown
  598. """ Return self*value.n """
  599. pass
  600.  
  601. @staticmethod # known case of __new__
  602. def __new__(*args, **kwargs): # real signature unknown
  603. """ Create and return a new object. See help(type) for accurate signature. """
  604. pass
  605.  
  606. def __ne__(self, *args, **kwargs): # real signature unknown
  607. """ Return self!=value. """
  608. pass
  609.  
  610. def __repr__(self, *args, **kwargs): # real signature unknown
  611. """ Return repr(self). """
  612. pass
  613.  
  614. def __rmod__(self, *args, **kwargs): # real signature unknown
  615. """ Return value%self. """
  616. pass
  617.  
  618. def __rmul__(self, *args, **kwargs): # real signature unknown
  619. """ Return self*value. """
  620. pass
  621.  
  622. def __sizeof__(self): # real signature unknown; restored from __doc__
  623. """ S.__sizeof__() -> size of S in memory, in bytes """
  624. pass
  625.  
  626. def __str__(self, *args, **kwargs): # real signature unknown
  627. """ Return str(self). """
  628. pass

字符串源码

常用字符串操作:

  1. # 1、casefold() : 将字符串的所有字符变小写。
  2. s = "HYPlcy"
  3. print(s.casefold()) # 结果:hyplcy
  4.  
  5. # 2、count(sub[,start[,end]]) : 查找子字符串出现的次数
  6. str1 = "asdfgasdfgasert"
  7. print(str1.count("as"))
  8.  
  9. # 3、index(sub[,start[,end]]) : 查找子字符串在该字符串中的位置,找到了返回第一个字符的索引值
  10. # 找不到会抛出异常。与find(sub[,start[,end]])类似,找不到返回-1.
  11. str2 = "Welcome hyp"
  12. print(str2.index("lc"))
  13. print(str2.index("lc",2,6))
  14. print(str2.find("lc",1,6))
  15. print(str2.find("lc",2,6))
  16.  
  17. # 4、join() : 连接字符串
  18. str3 = '-'.join(['hyp','lcy','abc'])
  19. print(str3)
  20.  
  21. # 5、replace(old,new[,count]) : 替换指定的字符串
  22. str4 = "hello hyp"
  23. print(str4.replace("hyp","lcy"))
  24.  
  25. # 6、split(): 用于拆分字符串
  26. str5 = "h_y_p_l"
  27. print(str5.split('_'))
  28.  
  29. # 7、capitalize(): capitalize方法判断字符串的首位是否为字母,是则 将该字母大写,其余字母小写
  30. str6 = "hyp"
  31. print(str6.capitalize())
  32.  
  33. # 8、center(): 设置宽度,并将内容居中
  34. str7 = "hyp"
  35. print(str7.center(20))
  36. print(str7.center(20,"-"))
  37.  
  38. # 9、startswith,endswith 以什么开头、结尾
  39. str8 = "hyplcy"
  40. print(str8.startswith("hy"))
  41. print(str8.endswith("cy"))
  42.  
  43. # 10、format(): 格式化,将格式化的占位符替换为指定的值
  44. str9 = 'I am {name} ,{age}'
  45. print(str9.format(name = 'hyp',age = '18'))
  46.  
  47. # 11、len、isnumeric、 isdigit、upper、swapcase(大小写互换)......

二、列表

  1. class list(object):
  2. """
  3. list() -> new empty list
  4. list(iterable) -> new list initialized from iterable's items
  5. """
  6. def append(self, p_object): # real signature unknown; restored from __doc__
  7. """ L.append(object) -> None -- append object to end """
  8. pass
  9.  
  10. def clear(self): # real signature unknown; restored from __doc__
  11. """ L.clear() -> None -- remove all items from L """
  12. pass
  13.  
  14. def copy(self): # real signature unknown; restored from __doc__
  15. """ L.copy() -> list -- a shallow copy of L """
  16. return []
  17.  
  18. def count(self, value): # real signature unknown; restored from __doc__
  19. """ L.count(value) -> integer -- return number of occurrences of value """
  20. return 0
  21.  
  22. def extend(self, iterable): # real signature unknown; restored from __doc__
  23. """ L.extend(iterable) -> None -- extend list by appending elements from the iterable """
  24. pass
  25.  
  26. def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
  27. """
  28. L.index(value, [start, [stop]]) -> integer -- return first index of value.
  29. Raises ValueError if the value is not present.
  30. """
  31. return 0
  32.  
  33. def insert(self, index, p_object): # real signature unknown; restored from __doc__
  34. """ L.insert(index, object) -- insert object before index """
  35. pass
  36.  
  37. def pop(self, index=None): # real signature unknown; restored from __doc__
  38. """
  39. L.pop([index]) -> item -- remove and return item at index (default last).
  40. Raises IndexError if list is empty or index is out of range.
  41. """
  42. pass
  43.  
  44. def remove(self, value): # real signature unknown; restored from __doc__
  45. """
  46. L.remove(value) -> None -- remove first occurrence of value.
  47. Raises ValueError if the value is not present.
  48. """
  49. pass
  50.  
  51. def reverse(self): # real signature unknown; restored from __doc__
  52. """
  53. 翻转
  54. L.reverse() -- reverse *IN PLACE* """
  55. pass
  56.  
  57. def sort(self, key=None, reverse=False): # real signature unknown; restored from __doc__
  58. """
  59. 排序
  60. L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """
  61. pass
  62.  
  63. def __add__(self, *args, **kwargs): # real signature unknown
  64. """ Return self+value. """
  65. pass
  66.  
  67. def __contains__(self, *args, **kwargs): # real signature unknown
  68. """ Return key in self. """
  69. pass
  70.  
  71. def __delitem__(self, *args, **kwargs): # real signature unknown
  72. """ Delete self[key]. """
  73. pass
  74.  
  75. def __eq__(self, *args, **kwargs): # real signature unknown
  76. """ Return self==value. """
  77. pass
  78.  
  79. def __getattribute__(self, *args, **kwargs): # real signature unknown
  80. """ Return getattr(self, name). """
  81. pass
  82.  
  83. def __getitem__(self, y): # real signature unknown; restored from __doc__
  84. """ x.__getitem__(y) <==> x[y] """
  85. pass
  86.  
  87. def __ge__(self, *args, **kwargs): # real signature unknown
  88. """ Return self>=value. """
  89. pass
  90.  
  91. def __gt__(self, *args, **kwargs): # real signature unknown
  92. """ Return self>value. """
  93. pass
  94.  
  95. def __iadd__(self, *args, **kwargs): # real signature unknown
  96. """ Implement self+=value. """
  97. pass
  98.  
  99. def __imul__(self, *args, **kwargs): # real signature unknown
  100. """ Implement self*=value. """
  101. pass
  102.  
  103. def __init__(self, seq=()): # known special case of list.__init__
  104. """
  105. list() -> new empty list
  106. list(iterable) -> new list initialized from iterable's items
  107. # (copied from class doc)
  108. """
  109. pass
  110.  
  111. def __iter__(self, *args, **kwargs): # real signature unknown
  112. """ Implement iter(self). """
  113. pass
  114.  
  115. def __len__(self, *args, **kwargs): # real signature unknown
  116. """ Return len(self). """
  117. pass
  118.  
  119. def __le__(self, *args, **kwargs): # real signature unknown
  120. """ Return self<=value. """
  121. pass
  122.  
  123. def __lt__(self, *args, **kwargs): # real signature unknown
  124. """ Return self<value. """
  125. pass
  126.  
  127. def __mul__(self, *args, **kwargs): # real signature unknown
  128. """ Return self*value.n """
  129. pass
  130.  
  131. @staticmethod # known case of __new__
  132. def __new__(*args, **kwargs): # real signature unknown
  133. """ Create and return a new object. See help(type) for accurate signature. """
  134. pass
  135.  
  136. def __ne__(self, *args, **kwargs): # real signature unknown
  137. """ Return self!=value. """
  138. pass
  139.  
  140. def __repr__(self, *args, **kwargs): # real signature unknown
  141. """ Return repr(self). """
  142. pass
  143.  
  144. def __reversed__(self): # real signature unknown; restored from __doc__
  145. """ L.__reversed__() -- return a reverse iterator over the list """
  146. pass
  147.  
  148. def __rmul__(self, *args, **kwargs): # real signature unknown
  149. """ Return self*value. """
  150. pass
  151.  
  152. def __setitem__(self, *args, **kwargs): # real signature unknown
  153. """ Set self[key] to value. """
  154. pass
  155.  
  156. def __sizeof__(self): # real signature unknown; restored from __doc__
  157. """ L.__sizeof__() -- size of L in memory, in bytes """
  158. pass
  159.  
  160. __hash__ = None

list源码

创建列表

  1. names = ['hyp',"lcy",'me']

通过下标访问列表中的元素,下标从0开始计数

  1. >>> names[0]
  2. 'hyp'
  3. >>> names[2]
  4. 'me'
  5. >>> names[-1]
  6. 'me'
  7. >>> names[-2] #还可以倒着取
  8. 'lcy'

切片:取多个元素

  1. >>> names = ["hyp","lcy","me","you","he","she"]
  2. >>> names[1:4] #取下标1至下标4之间的数字,包括1,不包括4
  3. ["lcy","me","you"]
  4. >>> names[1:-1] #取下标1至-1的值,不包括-1
  5. ["lcy","me","you","he","she"]
  6. >>> names[0:3]
  7. ["hyp","lcy","me"]
  8. >>> names[:3] #如果是从头开始取,0可以忽略,跟上句效果一样
  9. ["hyp","lcy","me"]
  10. >>> names[3:] #如果想取最后一个,必须不能写-1,只能这么写
  11. ["you","he","she"]
  12. >>> names[3:-1] #这样-1就不会被包含了
  13. ["you","he"]
  14. >>> names[0::2] #后面的2是代表,每隔一个元素,就取一个
  15. ["hyp","me","he"]
  16. ]>>> names[::2] #和上句效果一样
  17. ["hyp","me","he"]

追加

  1. >>> names
  2. ['hyp','lcy','me','he','she']
  3. >>> names.append("我是新来的")
  4. >>> names
  5. ['hyp','lcy','me','he','she', '我是新来的']

插入

  1. >>> names
  2. ['hyp','lcy','me','he','she']
  3. >>> names.insert(2,"强行从前面插入")
  4. >>> names
  5. ['hyp', 'lcy', '强行从me前面插入','he','she','我是新来的']

修改

  1. >>> names
  2. ['Alex', 'Tenglan', '强行从Eric前面插入', 'Eric', 'Rain', '从eric后面插入试试新姿势', 'Tom', 'Amy', '我是新来的']
  3. >>> names[2] = "该换人了"
  4. >>> names
  5. ['Alex', 'Tenglan', '该换人了', 'Eric', 'Rain', '从eric后面插入试试新姿势', 'Tom', 'Amy', '我是新来的']

删除

  1. >>> del names[2]
  2. >>> names
  3. ['Alex', 'Tenglan', 'Eric', 'Rain', '从eric后面插入试试新姿势', 'Tom', 'Amy', '我是新来的']
  4. >>> del names[4]
  5. >>> names
  6. ['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy', '我是新来的']
  7. >>>
  8. >>> names.remove("Eric") #删除指定元素
  9. >>> names
  10. ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', '我是新来的']
  11. >>> names.pop() #删除列表最后一个值
  12. '我是新来的'
  13. >>> names
  14. ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy']

扩展

  1. >>> names
  2. ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy']
  3. >>> b = [1,2,3]
  4. >>> names.extend(b)
  5. >>> names
  6. ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', 1, 2, 3]

拷贝

  1. >>> names
  2. ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', 1, 2, 3]
  3.  
  4. >>> name_copy = names.copy()
  5. >>> name_copy
  6. ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', 1, 2, 3]

统计

  1. >>> names
  2. ['Alex', 'Tenglan', 'Amy', 'Tom', 'Amy', 1, 2, 3]
  3. >>> names.count("Amy")
  4. 2

排序&翻转

  1. >>> names
  2. ['Alex', 'Tenglan', 'Amy', 'Tom', 'Amy', 1, 2, 3]
  3. >>> names.sort() #排序
  4. Traceback (most recent call last):
  5. File "<stdin>", line 1, in <module>
  6. TypeError: unorderable types: int() < str() #3.0里不同数据类型不能放在一起排序了,擦
  7. >>> names[-3] = ''
  8. >>> names[-2] = ''
  9. >>> names[-1] = ''
  10. >>> names
  11. ['Alex', 'Amy', 'Amy', 'Tenglan', 'Tom', '', '', '']
  12. >>> names.sort()
  13. >>> names
  14. ['', '', '', 'Alex', 'Amy', 'Amy', 'Tenglan', 'Tom']
  15.  
  16. >>> names.reverse() #反转
  17. >>> names
  18. ['Tom', 'Tenglan', 'Amy', 'Amy', 'Alex', '', '', '']

获取下标

  1. >>> names
  2. ['Tom', 'Tenglan', 'Amy', 'Amy', 'Alex', '', '', '']
  3. >>> names.index("Amy")
  4. 2 #只返回找到的第一个下标

三、元组

创建元组

  1. tuple1 = (1,2,3,4,5,6)

访问元组的方式与列表一样

  1. tuple1 = (1,2,3,4,5,6)
  2. print(tuple1[1])
  3. print(tuple1[3:])
  4. print(tuple1[2:4])

分片

  1. tuple1 = (1,2,3,4,5,6)
  2. tuple2 = tuple1[:] # 复制
  3.  
  4. temp = () # 创建空元组
  5. temp1 = (1,) # 只有一个元素,在它后面加上逗号(,)

四、字典 (无序)

字典是Python语言中唯一的映射类型。

  1. class dict(object):
  2. """
  3. dict() -> new empty dictionary # 空字典
  4. dict(mapping) -> new dictionary initialized from a mapping object's
  5. (key, value) pairs
  6. dict(iterable) -> new dictionary initialized as if via:
  7. d = {}
  8. for k, v in iterable:
  9. d[k] = v
  10. dict(**kwargs) -> new dictionary initialized with the name=value pairs
  11. in the keyword argument list. For example: dict(one=1, two=2)
  12. """
  13. def clear(self): # real signature unknown; restored from __doc__
  14. """ D.clear() -> None. Remove all items from D. """
  15. pass
  16.  
  17. def copy(self): # real signature unknown; restored from __doc__
  18. """
  19. 复制字典
  20. D.copy() -> a shallow copy of D
  21. """
  22. pass
  23.  
  24. @staticmethod # known case
  25. def fromkeys(*args, **kwargs): # real signature unknown
  26. # 创建并返回一个新字典,有两个参数,一:字典的键;二,可选,传入键的值,默认是 None
  27. """ Returns a new dict with keys from iterable and values equal to value. """
  28. pass
  29.  
  30. def get(self, k, d=None): # real signature unknown; restored from __doc__
  31. # 更宽松的访问字典项,当键不存在时,不会报错,返回None.
  32. """ D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """
  33. pass
  34.  
  35. def items(self): # real signature unknown; restored from __doc__
  36. # 返回字典中所有的键值对(项)
  37. """ D.items() -> a set-like object providing a view on D's items """
  38. pass
  39.  
  40. def keys(self): # real signature unknown; restored from __doc__
  41. """ D.keys() -> a set-like object providing a view on D's keys """
  42. pass
  43.  
  44. def pop(self, k, d=None): # real signature unknown; restored from __doc__
  45. """
  46. 给定键弹出对应的值
  47. D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
  48. If key is not found, d is returned if given, otherwise KeyError is raised
  49. """
  50. pass
  51.  
  52. def popitem(self): # real signature unknown; restored from __doc__
  53. """
  54. 随机弹出一个项
  55. D.popitem() -> (k, v), remove and return some (key, value) pair as a
  56. 2-tuple; but raise KeyError if D is empty.
  57. """
  58. pass
  59.  
  60. def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
  61. """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
  62. pass
  63.  
  64. def update(self, E=None, **F): # known special case of dict.update
  65. """
  66. 更新字典
  67. D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
  68. If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
  69. If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
  70. In either case, this is followed by: for k in F: D[k] = F[k]
  71. """
  72. pass
  73.  
  74. def values(self): # real signature unknown; restored from __doc__
  75. """ D.values() -> an object providing a view on D's values """
  76. pass
  77.  
  78. def __contains__(self, *args, **kwargs): # real signature unknown
  79. """ True if D has a key k, else False. """
  80. pass
  81.  
  82. def __delitem__(self, *args, **kwargs): # real signature unknown
  83. """ Delete self[key]. """
  84. pass
  85.  
  86. def __eq__(self, *args, **kwargs): # real signature unknown
  87. """ Return self==value. """
  88. pass
  89.  
  90. def __getattribute__(self, *args, **kwargs): # real signature unknown
  91. """ Return getattr(self, name). """
  92. pass
  93.  
  94. def __getitem__(self, y): # real signature unknown; restored from __doc__
  95. """ x.__getitem__(y) <==> x[y] """
  96. pass
  97.  
  98. def __ge__(self, *args, **kwargs): # real signature unknown
  99. """ Return self>=value. """
  100. pass
  101.  
  102. def __gt__(self, *args, **kwargs): # real signature unknown
  103. """ Return self>value. """
  104. pass
  105.  
  106. def __init__(self, seq=None, **kwargs): # known special case of dict.__init__
  107. """
  108. dict() -> new empty dictionary
  109. dict(mapping) -> new dictionary initialized from a mapping object's
  110. (key, value) pairs
  111. dict(iterable) -> new dictionary initialized as if via:
  112. d = {}
  113. for k, v in iterable:
  114. d[k] = v
  115. dict(**kwargs) -> new dictionary initialized with the name=value pairs
  116. in the keyword argument list. For example: dict(one=1, two=2)
  117. # (copied from class doc)
  118. """
  119. pass
  120.  
  121. def __iter__(self, *args, **kwargs): # real signature unknown
  122. """ Implement iter(self). """
  123. pass
  124.  
  125. def __len__(self, *args, **kwargs): # real signature unknown
  126. """ Return len(self). """
  127. pass
  128.  
  129. def __le__(self, *args, **kwargs): # real signature unknown
  130. """ Return self<=value. """
  131. pass
  132.  
  133. def __lt__(self, *args, **kwargs): # real signature unknown
  134. """ Return self<value. """
  135. pass
  136.  
  137. @staticmethod # known case of __new__
  138. def __new__(*args, **kwargs): # real signature unknown
  139. """ Create and return a new object. See help(type) for accurate signature. """
  140. pass
  141.  
  142. def __ne__(self, *args, **kwargs): # real signature unknown
  143. """ Return self!=value. """
  144. pass
  145.  
  146. def __repr__(self, *args, **kwargs): # real signature unknown
  147. """ Return repr(self). """
  148. pass
  149.  
  150. def __setitem__(self, *args, **kwargs): # real signature unknown
  151. """ Set self[key] to value. """
  152. pass
  153.  
  154. def __sizeof__(self): # real signature unknown; restored from __doc__
  155. """ D.__sizeof__() -> size of D in memory, in bytes """
  156. pass
  157.  
  158. __hash__ = None

dict源码

字典的定义与特性

定义:{key1:value1,key2:value2}

特性:

  1. 1key-value 结构
  2.  
  3. 2key必须可hash,且必须为不可变数据类型,必须唯一
  4.  
  5. 3、可存放任意多个值,可修改,可以不唯一
  6.  
  7. 4、无序

字典的创建

  1. person = {"name": "hyp", "age": 18}
  2.  
  3. person1 = dict(name='lcy', age=19)
  4.  
  5. person2 = dict({"name": "sfv", "age": 20})
  6.  
  7. person3 = dict((['name','hyp'],['lcy',20]))
  8. {}.fromkeys(seq,100) # 不指定100,默认为None
  9.  
  10. # 注意
  11. >>> dic = {}.fromkeys(['k1','k2'],[])
  12. >>> dic
  13. {'k1': [], 'k2': []}
  14. >>> dic['k1'].append(1)
  15. >>> dic
  16. {'k1': [1], 'k2': [1]}

常见操作

  1. 键、值、键值对
  2. 1dic.keys() 返回一个包含字典所有key的列表
  3. 2dic.values() 返回一个包含字典所有value 的列表
  4. 3dic.items() 返回一个包含所有(键、值)元组的列表
  5. 4dic.iteritems()、dic.iterkeys()、dic.itervalues() 与它们对应的非迭代方法一样,不同的是它们返回一个迭代子,而不是一个列表。
  6.  
  7. 新增
  8. 1dic['new_key'] = 'new_value';
  9. 2dic.setdefault(key,None) , 如果字典中存在key 键,就不做修改,没有就添加,有返回值。
  10.  
  11. 查看
  12. 1dic['key']
  13. 2dict.get(key,default = None)
  14.  
  15. 循环
  16. 1for k in dic
  17. 2for k in dic.keys()
  18. 3for k in dic.items()
  19.  
  20. 长度
  21. len(dic)

五、集合 (无序,可遍历)

集合的工厂函数

  1. class set(object):
  2. """
  3. set() -> new empty set object
  4. set(iterable) -> new set object
  5.  
  6. Build an unordered collection of unique elements.
  7. """
  8.  
  9. def add(self, *args, **kwargs): # real signature unknown
  10. """
  11. Add an element to a set.
  12.  
  13. This has no effect if the element is already present.
  14. """
  15. pass
  16.  
  17. def clear(self, *args, **kwargs): # real signature unknown
  18. """ Remove all elements from this set. """
  19. pass
  20.  
  21. def copy(self, *args, **kwargs): # real signature unknown
  22. """ Return a shallow copy of a set. """
  23. pass
  24.  
  25. def difference(self, *args, **kwargs): # real signature unknown
  26. """
  27. 相当于 s1-s2
  28. Return the difference of two or more sets as a new set.
  29.  
  30. (i.e. all elements that are in this set but not the others.)
  31. """
  32. pass
  33.  
  34. def difference_update(self, *args, **kwargs): # real signature unknown
  35. """ Remove all elements of another set from this set. """
  36. pass
  37.  
  38. def discard(self, *args, **kwargs): # real signature unknown
  39. """
  40. 与 remove 功能相同,删除元素不存在时不会抛出异常;
  41. Remove an element from a set if it is a member.
  42.  
  43. If the element is not a member, do nothing.
  44. """
  45. pass
  46.  
  47. def intersection(self, *args, **kwargs): # real signature unknown
  48. """
  49. 相当于 s1&s2
  50. Return the intersection of two sets as a new set.
  51.  
  52. (i.e. all elements that are in both sets.)
  53. """
  54. pass
  55.  
  56. def intersection_update(self, *args, **kwargs): # real signature unknown
  57. """ Update a set with the intersection of itself and another. """
  58. pass
  59.  
  60. def isdisjoint(self, *args, **kwargs): # real signature unknown
  61. """ Return True if two sets have a null intersection. """
  62. pass
  63.  
  64. def issubset(self, *args, **kwargs): # real signature unknown
  65. """
  66. 相当于 s1 <= s2
  67. Report whether another set contains this set. """
  68. pass
  69.  
  70. def issuperset(self, *args, **kwargs): # real signature unknown
  71. """
  72. 相当于 s1 >= s2
  73. Report whether this set contains another set. """
  74. pass
  75.  
  76. def pop(self, *args, **kwargs): # real signature unknown
  77. """
  78. Remove and return an arbitrary set element.
  79. Raises KeyError if the set is empty.
  80. """
  81. pass
  82.  
  83. def remove(self, *args, **kwargs): # real signature unknown
  84. """
  85. Remove an element from a set; it must be a member.
  86.  
  87. If the element is not a member, raise a KeyError.
  88. """
  89. pass
  90.  
  91. def symmetric_difference(self, *args, **kwargs): # real signature unknown
  92. """
  93. 相当于 s1^s2
  94. Return the symmetric difference of two sets as a new set.
  95.  
  96. (i.e. all elements that are in exactly one of the sets.)
  97. """
  98. pass
  99.  
  100. def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
  101. """ Update a set with the symmetric difference of itself and another. """
  102. pass
  103.  
  104. def union(self, *args, **kwargs): # real signature unknown
  105. """
  106. 相当于 s1|s2
  107.  
  108. Return the union of sets as a new set.
  109.  
  110. (i.e. all elements that are in either set.)
  111. """
  112. pass
  113.  
  114. def update(self, *args, **kwargs): # real signature unknown
  115. """ Update a set with the union of itself and others. """
  116. pass

set源码

三个特征:

  确定性、互异性(去重)、无序性

关系运算

  | ---> 并集,- :差集, ^ ---> 对称差集

包含关系

  1. innot in :判断某元素是否在集合内
  2.  
  3. ==,!= :判断两个集合是否相等

常用操作

  元素的增加

  1. add() :单个元素的增加
  2.  
  3. update():对序列的增加,可同时传入多个参数

  元素的删除

  方法一:

  元素不在原集合中时

  1. set.discard(x) 不会抛出异常
  2.  
  3. set.remove(x) 会抛出KeyError 错误
  4. pop():由于集合是无序的,pop 返回的结果是不能确定的,且当集合为空时,调用 pop 会抛出 KeyError 错误;
  5.  
  6. clear():清空集合

六、字符编码和转码

ASCII码

ASCII(American Standard Code for Information Interchange,美国信息交换标准代码)是基于拉丁字母的一套电脑编码系统,主要用于显示现代英语和其他西欧语言。它是现今最通用的单字节编码系统,并等同于国际标准ISO/IEC 646。

由于计算机是美国人发明的,因此,最早只有127个字母被编码到计算机里,也就是大小写英文字母、数字和一些符号,这个编码表被称为ASCII编码,比如大写字母 A的编码是65,小写字母 z的编码是122。后128个称为扩展ASCII码。

那现在我们就知道了上面的字母符号和数字对应的表是早就存在的。

在这里,每一位0或者1所占的空间单位为bit(比特),这是计算机中最小的表示单位

每8个bit组成一个字节,这是计算机中最小的存储单位(毕竟你是没有办法存储半个字符的)orz~

GBK和GB2312

显然,对于我们来说能在计算机中显示中文字符是至关重要的,然而刚学习的ASCII表里连一个偏旁部首也没有。所以我们还需要一张关于中文和数字对应的关系表。之前我们已经看到了,一个字节只能最多表示256个字符,要处理中文显然一个字节是不够的,所以我们需要采用两个字节来表示,而且还不能和ASCII编码冲突,所以,中国制定了GB2312编码,用来把中文编进去。

你可以想得到的是,全世界有上百种语言,日本把日文编到Shift_JIS里,韩国把韩文编到Euc-kr里,

各国有各国的标准,就会不可避免地出现冲突,结果就是,在多语言混合的文本中,显示出来会有乱码。

Unicode

因此,Unicode应运而生。Unicode把所有语言都统一到一套编码里,这样就不会再有乱码问题了。

Unicode标准也在不断发展,但最常用的是用两个字节表示一个字符(如果要用到非常偏僻的字符,就需要4个字节)。现代操作系统和大多数编程语言都直接支持Unicode。

现在,捋一捋ASCII编码和Unicode编码的区别:

ASCII编码是1个字节,而Unicode编码通常是2个字节。

字母A用ASCII编码是十进制的65,二进制的01000001;

字符0用ASCII编码是十进制的48,二进制的00110000;

汉字“中”已经超出了ASCII编码的范围,用Unicode编码是十进制的20013,二进制的01001110 00101101。

你可以猜测,如果把ASCII编码的A用Unicode编码,只需要在前面补0就可以,因此,A的Unicode编码是00000000 01000001。

新的问题又出现了:如果统一成Unicode编码,乱码问题从此消失了。但是,如果你写的文本基本上全部是英文的话,用Unicode编码比ASCII编码需要多一倍的存储空间,在存储和传输上就十分不划算。

UTF-8

所以,本着节约的精神,又出现了把Unicode编码转化为“可变长编码”的UTF-8编码。UTF-8编码把一个Unicode字符根据不同的数字大小编码成1-6个字节,常用的英文字母被编码成1个字节,汉字通常是3个字节,只有很生僻的字符才会被编码成4-6个字节。如果你要传输的文本包含大量英文字符,用UTF-8编码就能节省空间:

搞清楚了ASCII、Unicode和UTF-8的关系,我们就可以总结一下现在计算机系统通用的字符编码工作方式:

在计算机内存中,统一使用Unicode编码,当需要保存到硬盘或者需要传输的时候,就转换为UTF-8编码。

用记事本编辑的时候,从文件读取的UTF-8字符被转换为Unicode字符到内存里,编辑完成后,保存的时候再把Unicode转换为UTF-8保存到文件。

Python全栈开发之路 【第二篇】:Python基础之数据类型的更多相关文章

  1. Python全栈开发记录_第二篇(文件操作及三级菜单栏增删改查)

    python3文件读写操作(本篇代码大约100行) f = open(xxx.txt, "r", encoding="utf-8") 不写“r”(只读)默认是只 ...

  2. python 全栈开发之路 day1

    python 全栈开发之路 day1   本节内容 计算机发展介绍 计算机硬件组成 计算机基本原理 计算机 计算机(computer)俗称电脑,是一种用于高速计算的电子计算机器,可以进行数值计算,又可 ...

  3. Python 全栈开发【第0篇】:目录

    Python 全栈开发[第0篇]:目录   第一阶段:Python 开发入门 Python 全栈开发[第一篇]:计算机原理&Linux系统入门 Python 全栈开发[第二篇]:Python基 ...

  4. Python全栈开发记录_第一篇(循环练习及杂碎的知识点)

    Python全栈开发记录只为记录全栈开发学习过程中一些难和重要的知识点,还有问题及课后题目,以供自己和他人共同查看.(该篇代码行数大约:300行) 知识点1:优先级:not>and 短路原则:a ...

  5. Python全栈开发之路 【第四篇】:Python基础之函数

    本节内容 函数def: 1.位置参数,默认参数 2.位置参数,关键参数 3.如果参数中出现 *users,传递的参数就可以不再是固定的个数, 传过来的所有元素进行打包成元组 *args,**kwarg ...

  6. Python全栈开发之路 【第七篇】:面向对象编程设计与开发(1)

    本节内容 一.编程范式 编程指的是写程序.敲代码,就是指程序员用特定的语法.数据结构和算法编写的代码,目的是来告诉计算机如何执行任务的. 在编程的世界里最常见的两大流派是:面向过程与面向对象.“功夫的 ...

  7. Python全栈开发之路 【第一篇】:Python 介绍

    本节内容 一.Python介绍 python的创始人为荷兰人——吉多·范罗苏姆(Guido van Rossum).1989年的圣诞节期间,吉多·范罗苏姆为了在阿姆斯特丹打发时间,决心开发一个新的脚本 ...

  8. Python全栈开发之路 【第八篇】:面向对象编程设计与开发(2)

    一.继承与派生 什么是继承? 继承指的是类与类之间的关系,是一种什么是什么的关系,继承的功能之一就是用来解决代码重用问题. 继承是一种创建新的类的方式,在python中,新建的类可以继承一个或多个父类 ...

  9. Python全栈开发之路 【第六篇】:Python基础之常用模块

    本节内容 模块分类: 好处: 标准库: help("modules") 查看所有python自带模块列表 第三方开源模块: 自定义模块: 模块调用: import module f ...

随机推荐

  1. c/c++链队列

    链队列 链队列就是简化了的单链表 nodequeue.h #ifndef __NODEQUEUE__ #define __NODEQUEUE__ #include <stdio.h> #i ...

  2. 两层c:forEach循环嵌套

    jsp中两级菜单如何用c:forEach输出 items 要被循环的信息 否 无 begin 开始的元素(0=第一个元素,1=第二个元素) 否 0 end 最后一个元素(0=第一个元素,1=第二个元素 ...

  3. Microsoft SQL Server sa 账户 登录错误18456

    分析:在安装Sql server 2012的时候,服务器身份验证没有选择“SQL Server 和 Windows身份验证模式(S)”,导致SQL Server身份验证方式被禁用. 操作: 以Wind ...

  4. 学习flying logic

    之前在知乎上结识的朋友吴笛,他的qq空间里分享了  flying logic的一些用途,我想到可以规划和团队的目标,这点让我感到很兴奋,分享学习这个软件. 学习之前,我应当把软件中的单词学明白.现在就 ...

  5. Docker+Nextcloud快速部署个人网盘

    各位大佬好,,,萌新顾北清又回来更新了,今天要快速部署一个人网盘. 有多快呢,,,5分钟吧,因为我们使用Docker部署. Docker基础可以看看我之前的博文.(点这里点这里) 那么,,,开始吧. ...

  6. mysql 数据备份与数据导入到出

    一.数据备份 #1. 物理备份: 直接复制数据库文件,适用于大型数据库环境.但不能恢复到异构系统中如Windows. #2. 逻辑备份: 备份的是建表.建库.插入等操作所执行SQL语句,适用于中小型数 ...

  7. mysql 数据可视化操作---Navicat安装及简单使用

    ,一.安装 下载地址:https://pan.baidu.com/s/1bpo5mqj 安装方法:https://www.cnblogs.com/clschao/articles/10022040.h ...

  8. hdfs fsck命令查看HDFS文件对应的文件块信息(Block)和位置信息(Locations)

    关键字:hdfs fsck.block.locations 在HDFS中,提供了fsck命令,用于检查HDFS上文件和目录的健康状态.获取文件的block信息和位置信息等. fsck命令必须由HDFS ...

  9. Codeforces Round #546 (Div. 2) C. Nastya Is Transposing Matrices

    C. Nastya Is Transposing Matrices time limit per test 1 second memory limit per test 256 megabytes i ...

  10. 【弱省胡策】Round #5 Count

    [弱省胡策]Round #5 Count 太神仙了. \(DP\)做法 设\(f_{n,m,d,k}\)表示\(n*m\)的矩阵,填入第\(k\)个颜色,并且第\(k\)个颜色最少的一列上有\(d\) ...