1、编码转换

unicode 可以编译成 UTF-U GBK

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. a = '测试字符' #默认是utf-8
  4. a_unicode = a.decode('utf-8') # decode是解码成unicode 括号是脚本内容的默认编码 即:将脚本内容的utf-8解码成unicode
  5. a_gbk = a_unicode.encode('gbk') #encode是编码,将unicode的编码内容编码成指定的,这里是gbk
  6. print(a_gbk) #用于终端打印
  7. print(u"测试字符二") #3里面是字符串 2里面是unicode
  8.  
  9. #3版本直接将utf-8编码成GBK 不需要先转成unicode了

2、pycharm的基本配置

1、file-setings-editor- file && file encode template  Python Script输入 以下内容作为声明模板

  1. #!/usr/bin/env python
  2. # _*_ coding:utf-8 _*_

2、View-Active Editor 勾选Use Soft Wraps 开启自动换行

3、在设置中,搜索encoding,可以修改编码规则

4、简单的快捷键

ctrl+/ 批量注释,取消注释

shift+方向键 选中

shift+tab 向左tab

5、

切换py版本

file -> settings ->project interpreter ->选择版本

3、运算符

1、算数运算:

2、比较运算:

3、赋值运算:

4、逻辑运算:

5、成员运算:

运算符

名称

说明

例子

+

两个对象相加

3 + 5得到8。'a' + 'b'得到'ab'。

-

得到负数或是一个数减去另一个数

-5.2得到一个负数。50 - 24得到26。

*

两个数相乘或是返回一个被重复若干次的字符串

2 * 3得到6。'la' * 3得到'lalala'。

**

返回x的y次幂

3 ** 4得到81(即3 * 3 * 3 * 3)

/

x除以y

4/3得到1(整数的除法得到整数结果)。4.0/3或4/3.0得到1.3333333333333333

//

取整除

返回商的整数部分

4 // 3.0得到1.0

%

取模

返回除法的余数

8%3得到2。-25.5%2.25得到1.5

<<

左移

把一个数的比特向左移一定数目(每个数在内存中都表示为比特或二进制数字,即0和1)

2 << 2得到8。——2按比特表示为10

>>

右移

把一个数的比特向右移一定数目

11 >> 1得到5。——11按比特表示为1011,向右移动1比特后得到101,即十进制的5。

&

按位与

数的按位与

5 & 3得到1。

|

按位或

数的按位或

5 | 3得到7。

^

按位异或

数的按位异或

5 ^ 3得到6

~

按位翻转

x的按位翻转是-(x+1)

~5得到-6。

<

小于

返回x是否小于y。所有比较运算符返回1表示真,返回0表示假。这分别与特殊的变量True和False等价。注意,这些变量名的大写。

5 < 3返回0(即False)而3 < 5返回1(即True)。比较可以被任意连接:3 < 5 < 7返回True。

>

大于

返回x是否大于y

5 > 3返回True。如果两个操作数都是数字,它们首先被转换为一个共同的类型。否则,它总是返回False。

<=

小于等于

返回x是否小于等于y

x = 3; y = 6; x <= y返回True。

>=

大于等于

返回x是否大于等于y

x = 4; y = 3; x >= y返回True。

==

等于

比较对象是否相等

x = 2; y = 2; x == y返回True。x = 'str'; y = 'stR'; x == y返回False。x = 'str'; y = 'str'; x == y返回True。

!=

不等于

比较两个对象是否不相等

x = 2; y = 3; x != y返回True。

not

布尔“非”

如果x为True,返回False。如果x为False,它返回True。

x = True; not x返回False。

and

布尔“与”

如果x为False,x and y返回False,否则它返回y的计算值。

x = False; y = True; x and y,由于x是False,返回False。在这里,Python不会计算y,因为它知道这个表达式的值肯定是False(因为x是False)。这个现象称为短路计算。

or

布尔“或”

如果x是True,它返回True,否则它返回y的计算值。

x = True; y = False; x or y返回True。短路计算在这里也适用。

4、基本的数据类型

数字的方法都放在int类中,而数字是类的实例化。 如上图所示。

可以通过type(a),来查看数据类型,变量的地址用id(a),来查看

1、数字

int(整型)

  在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647
  在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807
  1. class int(object):
  2. """
  3. int(x=0) -> int or long
  4. int(x, base=10) -> int or long
  5.  
  6. Convert a number or string to an integer, or return 0 if no arguments
  7. are given. If x is floating point, the conversion truncates towards zero.
  8. If x is outside the integer range, the function returns a long instead.
  9.  
  10. If x is not a number or if base is given, then x must be a string or
  11. Unicode object representing an integer literal in the given base. The
  12. literal can be preceded by '+' or '-' and be surrounded by whitespace.
  13. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to
  14. interpret the base from the string as an integer literal.
  15. >>> int('0b100', base=0)
  16. """
  17. def bit_length(self):
  18. """ 返回表示该数字的时占用的最少位数 """
  19. """
  20. int.bit_length() -> int
  21.  
  22. Number of bits necessary to represent self in binary.
  23. >>> bin(37)
  24. '0b100101'
  25. >>> (37).bit_length()
  26. """
  27. return 0
  28.  
  29. def conjugate(self, *args, **kwargs): # real signature unknown
  30. """ 返回该复数的共轭复数 """
  31. """ Returns self, the complex conjugate of any int. """
  32. pass
  33.  
  34. def __abs__(self):
  35. """ 返回绝对值 """
  36. """ x.__abs__() <==> abs(x) """
  37. pass
  38.  
  39. def __add__(self, y):
  40. """ x.__add__(y) <==> x+y """
  41. pass
  42.  
  43. def __and__(self, y):
  44. """ x.__and__(y) <==> x&y """
  45. pass
  46.  
  47. def __cmp__(self, y):
  48. """ 比较两个数大小 """
  49. """ x.__cmp__(y) <==> cmp(x,y) """
  50. pass
  51.  
  52. def __coerce__(self, y):
  53. """ 强制生成一个元组 """
  54. """ x.__coerce__(y) <==> coerce(x, y) """
  55. pass
  56.  
  57. def __divmod__(self, y):
  58. """ 相除,得到商和余数组成的元组 """
  59. """ x.__divmod__(y) <==> divmod(x, y) """
  60. pass
  61.  
  62. def __div__(self, y):
  63. """ x.__div__(y) <==> x/y """
  64. pass
  65.  
  66. def __float__(self):
  67. """ 转换为浮点类型 """
  68. """ x.__float__() <==> float(x) """
  69. pass
  70.  
  71. def __floordiv__(self, y):
  72. """ x.__floordiv__(y) <==> x//y """
  73. pass
  74.  
  75. def __format__(self, *args, **kwargs): # real signature unknown
  76. pass
  77.  
  78. def __getattribute__(self, name):
  79. """ x.__getattribute__('name') <==> x.name """
  80. pass
  81.  
  82. def __getnewargs__(self, *args, **kwargs): # real signature unknown
  83. """ 内部调用 __new__方法或创建对象时传入参数使用 """
  84. pass
  85.  
  86. def __hash__(self):
  87. """如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等。"""
  88. """ x.__hash__() <==> hash(x) """
  89. pass
  90.  
  91. def __hex__(self):
  92. """ 返回当前数的 十六进制 表示 """
  93. """ x.__hex__() <==> hex(x) """
  94. pass
  95.  
  96. def __index__(self):
  97. """ 用于切片,数字无意义 """
  98. """ x[y:z] <==> x[y.__index__():z.__index__()] """
  99. pass
  100.  
  101. def __init__(self, x, base=10): # known special case of int.__init__
  102. """ 构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略 """
  103. """
  104. int(x=0) -> int or long
  105. int(x, base=10) -> int or long
  106.  
  107. Convert a number or string to an integer, or return 0 if no arguments
  108. are given. If x is floating point, the conversion truncates towards zero.
  109. If x is outside the integer range, the function returns a long instead.
  110.  
  111. If x is not a number or if base is given, then x must be a string or
  112. Unicode object representing an integer literal in the given base. The
  113. literal can be preceded by '+' or '-' and be surrounded by whitespace.
  114. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to
  115. interpret the base from the string as an integer literal.
  116. >>> int('0b100', base=0)
  117. # (copied from class doc)
  118. """
  119. pass
  120.  
  121. def __int__(self):
  122. """ 转换为整数 """
  123. """ x.__int__() <==> int(x) """
  124. pass
  125.  
  126. def __invert__(self):
  127. """ x.__invert__() <==> ~x """
  128. pass
  129.  
  130. def __long__(self):
  131. """ 转换为长整数 """
  132. """ x.__long__() <==> long(x) """
  133. pass
  134.  
  135. def __lshift__(self, y):
  136. """ x.__lshift__(y) <==> x<<y """
  137. pass
  138.  
  139. def __mod__(self, y):
  140. """ x.__mod__(y) <==> x%y """
  141. pass
  142.  
  143. def __mul__(self, y):
  144. """ x.__mul__(y) <==> x*y """
  145. pass
  146.  
  147. def __neg__(self):
  148. """ x.__neg__() <==> -x """
  149. pass
  150.  
  151. @staticmethod # known case of __new__
  152. def __new__(S, *more):
  153. """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
  154. pass
  155.  
  156. def __nonzero__(self):
  157. """ x.__nonzero__() <==> x != 0 """
  158. pass
  159.  
  160. def __oct__(self):
  161. """ 返回改值的 八进制 表示 """
  162. """ x.__oct__() <==> oct(x) """
  163. pass
  164.  
  165. def __or__(self, y):
  166. """ x.__or__(y) <==> x|y """
  167. pass
  168.  
  169. def __pos__(self):
  170. """ x.__pos__() <==> +x """
  171. pass
  172.  
  173. def __pow__(self, y, z=None):
  174. """ 幂,次方 """
  175. """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """
  176. pass
  177.  
  178. def __radd__(self, y):
  179. """ x.__radd__(y) <==> y+x """
  180. pass
  181.  
  182. def __rand__(self, y):
  183. """ x.__rand__(y) <==> y&x """
  184. pass
  185.  
  186. def __rdivmod__(self, y):
  187. """ x.__rdivmod__(y) <==> divmod(y, x) """
  188. pass
  189.  
  190. def __rdiv__(self, y):
  191. """ x.__rdiv__(y) <==> y/x """
  192. pass
  193.  
  194. def __repr__(self):
  195. """转化为解释器可读取的形式 """
  196. """ x.__repr__() <==> repr(x) """
  197. pass
  198.  
  199. def __str__(self):
  200. """转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式"""
  201. """ x.__str__() <==> str(x) """
  202. pass
  203.  
  204. def __rfloordiv__(self, y):
  205. """ x.__rfloordiv__(y) <==> y//x """
  206. pass
  207.  
  208. def __rlshift__(self, y):
  209. """ x.__rlshift__(y) <==> y<<x """
  210. pass
  211.  
  212. def __rmod__(self, y):
  213. """ x.__rmod__(y) <==> y%x """
  214. pass
  215.  
  216. def __rmul__(self, y):
  217. """ x.__rmul__(y) <==> y*x """
  218. pass
  219.  
  220. def __ror__(self, y):
  221. """ x.__ror__(y) <==> y|x """
  222. pass
  223.  
  224. def __rpow__(self, x, z=None):
  225. """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """
  226. pass
  227.  
  228. def __rrshift__(self, y):
  229. """ x.__rrshift__(y) <==> y>>x """
  230. pass
  231.  
  232. def __rshift__(self, y):
  233. """ x.__rshift__(y) <==> x>>y """
  234. pass
  235.  
  236. def __rsub__(self, y):
  237. """ x.__rsub__(y) <==> y-x """
  238. pass
  239.  
  240. def __rtruediv__(self, y):
  241. """ x.__rtruediv__(y) <==> y/x """
  242. pass
  243.  
  244. def __rxor__(self, y):
  245. """ x.__rxor__(y) <==> y^x """
  246. pass
  247.  
  248. def __sub__(self, y):
  249. """ x.__sub__(y) <==> x-y """
  250. pass
  251.  
  252. def __truediv__(self, y):
  253. """ x.__truediv__(y) <==> x/y """
  254. pass
  255.  
  256. def __trunc__(self, *args, **kwargs):
  257. """ 返回数值被截取为整形的值,在整形中无意义 """
  258. pass
  259.  
  260. def __xor__(self, y):
  261. """ x.__xor__(y) <==> x^y """
  262. pass
  263.  
  264. denominator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
  265. """ 分母 = 1 """
  266. """the denominator of a rational number in lowest terms"""
  267.  
  268. imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
  269. """ 虚数,无意义 """
  270. """the imaginary part of a complex number"""
  271.  
  272. numerator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
  273. """ 分子 = 数字大小 """
  274. """the numerator of a rational number in lowest terms"""
  275.  
  276. real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
  277. """ 实属,无意义 """
  278. """the real part of a complex number"""
  279.  
  280. int
2、布尔值
  真或假
  1 或 0
3、字符串
s1=“alex”
#encoding=""
#__init___.无参数创建空字符串。一个参数,创建普通字符串。两个参数,需要传字节和编码。创建字符串或转化字符串(需要知道编码)
s1=str("alex")
  1. "hello world"

字符串格式化

  1. name = "alex"
  2. print "i am %s " % name
  3.  
  4. #输出: i am alex

PS: 字符串是 %s;整数 %d;浮点数%f。浮点数小数位数%.2f 保留小数点后2位 %%s 百分号

单引号,双引号都可以表示字符串,里面可以插入另外的引号。三引号也可以表示字符串,支持换行的。

字符串常用功能:
  • 移除空白

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

字符串练习

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3.  
  4. # str字符串方法练习
  5. a = "alex"
  6. ret = a.capitalize() # 不用添加参数,字符串首字母变大写,str(object='') -> string
  7. print(ret)
  8. ret1 = a.center(20, "*") # 内容居中,width:总长度;fillchar:空白处填充内容,默认无。S.center(width[, fillchar]) -> string
  9. print(ret1)
  10. a2 = "alex is alph"
  11. ret2 = a2.count("al") # 计算子序列个数,def count(self, sub, start=None, end=None):,可定义开始和结束位置。S.count(sub[, start[, end]]) -> int
  12. ret3 = a2.count("a", 0)
  13. print(ret2, ret3)
  14.  
  15. ret4 = a2.endswith("alp", 0,-1) # """ 是否以 xxx 结束 """endswith(self, suffix, start=None, end=None):,可定义开始和结束的位置,S.endswith(suffix[, start[, end]]) -> bool
  16. print(a2.startswith("a")) # """ 是否以 xxx 开始 """ startswith(self, prefix, start=None, end=None):,可定义开始和结束的位置,S.startswith(prefix[, start[, end]]) -> bool
  17. print(ret4)
  18. a3 = "hello\t999" # """ 将tab转换成空格,默认一个tab转换成8个空格 """def expandtabs(self, tabsize=None):可以定义空格个数,S.expandtabs([tabsize]) -> string
  19. print(a3)
  20. print(a3.expandtabs(20))
  21.  
  22. s = "hello alex"
  23. s.find("al") # """ 寻找子序列位置,如果没找到,返回 -1 """def find(self, sub, start=None, end=None):可以定义开始和结束的位置,S.find(sub [,start [,end]]) -> int
  24. print(s.find("al"))
  25. s1 = "hello {0},age {1}" # {0},{1}可以充当占位符
  26. a4 = s1.format("alex",18) # """ 字符串格式化,动态参数,将函数式编程时细说 """def format(*args, **kwargs):S.format(*args, **kwargs) -> string
  27. print(s1, a4)
  28. print(s.index("ll")) # """ 子序列位置,如果没找到,报错 """ def index(self, sub, start=None, end=None):可以定义开始和结束的位置,S.index(sub [,start [,end]]) -> int
  29. num1 = "dasfsdfaa"
  30. num2 = "jkljljl"
  31. num3 = ""
  32. num4 = "kkk* &687689"
  33. num5 = " "
  34. num6 = "Alss Sss 888&&&L "
  35. num7 = "ALJL"
  36. print(num1.isalnum()) # """ 是否是字母或数字组成"""必须要字母和数字组成的字符串,含有其他字符返回FalseS.isalnum() -> bool
  37. print(num2.isalpha())
  38. # """ 是否全是字母 """
  39. print(num3.isdigit()) # """ 是否全是数字 """
  40. print(num4.islower()) # """ 这里面的字母是否小写 """可以包含其他字符
  41. print(num5.isspace())
  42. # 是否全是空格,且自少有一个字符
  43. print(num6.istitle()) # 是否是标题,所有首字母都是大写
  44. print(num7.title())
  45. # 变成标题
  46. print(num7.isupper())
  47. # 是否全是大写
  48. li = ["alex", "eric"]
  49. li2 = ("alex", "eric")
  50. print("_".join(li2))
  51. # """ 连接 """def join(self, iterable): 参数是可迭代的,循环li的元素,让每个元素用“_”连接起来
  52.  
  53. pp = "alexKKK000***1111"
  54. print(pp.ljust(20, "*"))
  55. # """ 内容左对齐,右侧填充 """width:总长度;fillchar:空白处填充内容,默认无。-> string
  56. print(pp.rjust(20, "*"))
  57. # 内容右对齐
  58. print(pp.lower())
  59. # 字母全部变成小写-> string
  60. print(pp.upper())
  61. # 字母全部变成大写-> string
  62. print(pp.swapcase())
  63. # 小写变大写,大写变小写
  64. kb = " kkkkfasdfa jkljlk "
  65. print(kb.lstrip())
  66. # """ 移除左侧空白 """
  67. print(kb.rstrip())
  68. # """ 移除右侧空白 """
  69. print(kb.strip())
  70. # """ 移除两侧的空白 """
  71.  
  72. sb = "alex SB alex SB"
  73. print(sb.partition("SB"))
  74. # """ 分割,前,中,后三部分 """添加到一个元祖里面S.partition(sep) -> (head, sep, tail)
  75. print(sb.replace("SB", "HH"))
  76. # """ 替换 """count参数是替换几个的意思
  77. print(sb.replace("SB", "HH", 1))
  78.  
  79. fg = "alexalex"
  80. print(fg.split("e"))
  81. # """ 分割, maxsplit最多分割几次 """S.split([sep [,maxsplit]]) -> list of strings
  82. print(fg.split("e", 1))
  83. fg1 = "alex\nalex"
  84. print(fg.splitlines()) # """ 根据换行分割 """

“jljl$ fsaldkfj6sdfjlasjdl”.title  数字特殊字符空格割开的第一个字母大写。

  1. print("abalex".strip("a")) outbalex
  1. print("aba*lex*".strip("a*")) outba*lex

4、列表

元素的集合就是列表,可变的一个元素集合
 

创建列表:

name_list = ['alex', 'seven', 'eric']
或name_list = list(['alex', 'seven', 'eric'])
创建列表,或将其他元素转化成列表
li="lsihu"
li_list=list(li) #将字符串转化成列表,只要是可迭代(能被for循环执行)的就可以转化,字符串、元祖、字典都可以转化成列表。
  1. name_list = ['alex', 'seven', 'eric']

  2. name_list list(['alex', 'seven', 'eric'])

基本操作:

    • 索引

      • name_list[0] #取一个,原来是什么类型元素,还是什么类型
    • 切片

      • name_list[0:2] #取出来多个元素,放到一个集合中是列表。
        name_list[2:len(name_list):2] 步长,步长-1时翻转

      增加

    • #追加,在原有基础后面添加
      list.append()
    • 扩展,extend
    • 插入,insert
  • 删除
    • pop,remove,clear,del
  • 长度
    • len(name_list)
  • 循环
    • for item in name_list:
      print item
  • 包含
    • if item in name_list
      return
  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. """ 添加 元素
  8.       L.append(object) -> None -- append object to end """
  9. pass
  10.  
  11. def clear(self): # real signature unknown; restored from __doc__
  12. """ 清空元素
  13.     L.clear() -> None -- remove all items from L """
  14. pass
  15.  
  16. def copy(self): # real signature unknown; restored from __doc__
  17. """ 浅copy L.copy() -> list -- a shallow copy of L """
  18. return []
  19.  
  20. def count(self, value): # real signature unknown; restored from __doc__
  21. """ 匹配 value的个数 L.count(value) -> integer -- return number of occurrences of value """
  22. return 0
  23.  
  24. def extend(self, iterable): # real signature unknown; restored from __doc__
  25. """ 拼接两个列表 L.extend(iterable) -> None -- extend list by appending elements from the iterable """
  26. pass
  27.  
  28. def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
  29. """ 返回 某个value 的索引
  30. L.index(value, [start, [stop]]) -> integer -- return first index of value.
  31. Raises ValueError if the value is not present.
  32. """
  33. return 0
  34.  
  35. def insert(self, index, p_object): # real signature unknown; restored from __doc__
  36. """ 指定索引位置处添加元素 L.insert(index, object) -- insert object before index """
  37. pass
  38.  
  39. def pop(self, index=None): # real signature unknown; restored from __doc__
  40. """ 删除结尾的元素
  41. L.pop([index]) -> item -- remove and return item at index (default last).
  42. Raises IndexError if list is empty or index is out of range.
  43. """
  44. pass
  45.  
  46. def remove(self, value): # real signature unknown; restored from __doc__
  47. """ 移除 从左测匹配的第一个元素
  48. L.remove(value) -> None -- remove first occurrence of value.
  49. Raises ValueError if the value is not present.
  50. """
  51. pass
  52.  
  53. def reverse(self): # real signature unknown; restored from __doc__
  54. """ 反转列表 L.reverse() -- reverse *IN PLACE* """
  55. pass
  56.  
  57. def sort(self, key=None, reverse=False): # real signature unknown; restored from __doc__
  58. """ 排序 但是int str不行 L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """
  59. pass
  60.  
  61. def __add__(self, *args, **kwargs): # real signature unknown
  62. """ Return self+value. """
  63. pass
  64.  
  65. def __contains__(self, *args, **kwargs): # real signature unknown
  66. """ Return key in self. """
  67. pass
  68.  
  69. def __delitem__(self, *args, **kwargs): # real signature unknown
  70. """ Delete self[key]. """
  71. pass
  72.  
  73. def __eq__(self, *args, **kwargs): # real signature unknown
  74. """ Return self==value. """
  75. pass
  76.  
  77. def __getattribute__(self, *args, **kwargs): # real signature unknown
  78. """ Return getattr(self, name). """
  79. pass
  80.  
  81. def __getitem__(self, y): # real signature unknown; restored from __doc__
  82. """ x.__getitem__(y) <==> x[y] """
  83. pass
  84.  
  85. def __ge__(self, *args, **kwargs): # real signature unknown
  86. """ Return self>=value. """
  87. pass
  88.  
  89. def __gt__(self, *args, **kwargs): # real signature unknown
  90. """ Return self>value. """
  91. pass
  92.  
  93. def __iadd__(self, *args, **kwargs): # real signature unknown
  94. """ Implement self+=value. """
  95. pass
  96.  
  97. def __imul__(self, *args, **kwargs): # real signature unknown
  98. """ Implement self*=value. """
  99. pass
  100.  
  101. def __init__(self, seq=()): # known special case of list.__init__
  102. """
  103. list() -> new empty list
  104. list(iterable) -> new list initialized from iterable's items
  105. # (copied from class doc)
  106. """
  107. pass
  108.  
  109. def __iter__(self, *args, **kwargs): # real signature unknown
  110. """ Implement iter(self). """
  111. pass
  112.  
  113. def __len__(self, *args, **kwargs): # real signature unknown
  114. """ Return len(self). """
  115. pass
  116.  
  117. def __le__(self, *args, **kwargs): # real signature unknown
  118. """ Return self<=value. """
  119. pass
  120.  
  121. def __lt__(self, *args, **kwargs): # real signature unknown
  122. """ Return self<value. """
  123. pass
  124.  
  125. def __mul__(self, *args, **kwargs): # real signature unknown
  126. """ Return self*value.n """
  127. pass
  128.  
  129. @staticmethod # known case of __new__
  130. def __new__(*args, **kwargs): # real signature unknown
  131. """ Create and return a new object. See help(type) for accurate signature. """
  132. pass
  133.  
  134. def __ne__(self, *args, **kwargs): # real signature unknown
  135. """ Return self!=value. """
  136. pass
  137.  
  138. def __repr__(self, *args, **kwargs): # real signature unknown
  139. """ Return repr(self). """
  140. pass
  141.  
  142. def __reversed__(self): # real signature unknown; restored from __doc__
  143. """ L.__reversed__() -- return a reverse iterator over the list """
  144. pass
  145.  
  146. def __rmul__(self, *args, **kwargs): # real signature unknown
  147. """ Return self*value. """
  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. """ L.__sizeof__() -- size of L in memory, in bytes """
  156. pass
  157.  
  158. __hash__ = None

示例:

  1. ###### 列表 ##########
  2.  
  3. #!/usr/bin/env python
  4. # _*_ coding:utf-8 _*_
  5.  
  6. lis=[1,2,3,'alex']
  7. cc=[5,5]
  8. print(lis.count("alex"))
  9. lis.extend(cc)
  10. print(lis)
  11.  
  12. name_list = ["eirc", "alex", 'tony']
  13. """
  14. # 索引
  15. print(name_list[0])
  16. # 切片
  17. print(name_list[0:2])
  18. # len
  19. print(name_list[2:len(name_list)])
  20. # for
  21. for i in name_list:
  22. print(i)
  23.  
  24. #join 方法,拼接字符串
  25. li = ["alex","eric"]
  26. name = "li jie"
  27. ss = "_".join(li)
  28. s = "_".join(name)
  29. print(s,ss)
  30.  
  31. """
  32. # 列表内部提供的其他功能
  33. # append后追加
  34. name_list.append('seven')
  35. name_list.append('seven')
  36. name_list.append('seven')
  37. print(name_list)
  38. # 元素出现的次数
  39. print(name_list.count('seven'))
  40. # iterable,可迭代的
  41. temp = [111,22,33,44]
  42. # 扩展,批量添加
  43. name_list.extend(temp)
  44. print(name_list)
  45. # 获取指定元素的索引位置
  46. print(name_list.index('alex'))
  47. # 向指定索引位置插入数据
  48. name_list.insert(1, 'SB')
  49. print(name_list)
  50. # 在原列表中移除掉最后一个元素,并将其赋值给 a1
  51. a1 = name_list.pop()
  52. print(name_list)
  53. print(a1)
  54. # 移除某个元素
  55. name_list.remove('seven')
  56. print(name_list)
  57. # 翻转
  58. name_list.reverse()
  59. print(name_list)
  60.  
  61. # 删除指定索引位置
  62. print(name_list)
  63. del name_list[1:3]
  64. print(name_list)

列表练习:

  1. # list列表方法练习
  2. name_list = ['alex', 'seven', 'eric']
  3.  
  4. #增加
  5. name_list.append("seven") # 在末尾追加
  6. name_list.append("seven")
  7. print(name_list)
  8.  
  9. temp = [11, "bb", 222]
  10. name_list.extend(temp) # 本身后面添加可迭代的参数,
  11. print(name_list)
  12. name_list.extend("abc") # 本身后面添加可迭代的参数
  13. print(name_list)
  14.  
  15. name_list.insert(1, "sb") # 在某个位置插入
  16. print(name_list)
  17.  
  18. #查找
  19. print(name_list.count("seven")) # 统计出现的次数
  20. # iterable可迭代的,只要能够通过for循环的 都是可迭代的。
  21.  
  22. print(name_list.index(11)) # 索引,查位置,参数:str,start,end。可以添加索引范围的。
  23.  
  24. #删除
  25. del name_list[1] #直接del删除,索引擅长,超出报错
  26. print(name_list)
  27. a = name_list.pop() # 默认尾部删掉,可赋值给别人,如果删完了会报错
  28. print(name_list, a)
  29. a = name_list.pop(2) #索引删除并赋值,如果超出索引报错
  30. print(name_list, a)
  31. x = name_list.remove("seven") # 只移除找到的第一个,不可赋值,找不到时报错
  32. print(name_list, x) #x是None,无法赋值
  33. # name_list.clear() #直接清空
  34.  
  35. name_list4 = ["eirc", "andy", "ALex"]
  36. del name_list4[1]
  37. # 删除列表指定位置的元素,索引位置,可用切片
  38. print(name_list4)
  39.  
  40. # 反转
  41. name_list.reverse() #列表翻转
  42. print(name_list)
  43.  
  44. # 排序,里面的元素类型必须一致
  45. name_list2 = [1, 2, 44, 52, 4, 2, 55, 2]
  46. name_list3 = ["kksaj", "jalkdjl", "ax", "bb"]
  47. name_list3.sort()
  48.  
  49. print(name_list3)
  1. #join 方法,拼接字符串
  1. #join 方法,拼接字符串
  2. li = ["alex","eric"]
  3. name = "li jie"
  4. ss = "_".join(li)
  5. s = "_".join(name)
  6. print(s,ss)

join是从可迭代的元素第一个元素后面开始拼接,在其他元素前面加上“ ”中的元素进行拼接

  1. print("_".join(["abc","ef"]))
  2. print("_".join("alex li"))
  3.  
  4. abc_ef
  5. a_l_e_x_ _l_i

5、元祖

创建元祖: 元组一旦创建 不等增加也不能减少

name_list = ('alex', 'seven', 'eric')#创建
name_list = tuple(['alex', 'seven', 'eric']) #转化,可以接收可迭代的对象。
基本操作:
  • 索引

    • name_list[0]
  • 切片
    • name_list[0:2]
      name_list[2:len(name_list):2]步长
  • 循环
    • for item in name_list:
      print item
  • 长度
    • len(name_list)
  • 包含
    • in
  1. class tuple(object):
  2. """
  3. tuple() -> empty tuple
  4. tuple(iterable) -> tuple initialized from iterable's items
  5.  
  6. If the argument is a tuple, the return value is the same object.
  7. """
  8. def count(self, value): # real signature unknown; restored from __doc__
  9. """ 计算 value的个数 T.count(value) -> integer -- return number of occurrences of value """
  10. return 0
  11.  
  12. def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
  13. """ 索引
  14. T.index(value, [start, [stop]]) -> integer -- return first index of value.
  15. Raises ValueError if the value is not present.
  16. """
  17. return 0
  18.  
  19. def __add__(self, *args, **kwargs): # real signature unknown
  20. """ Return self+value. """
  21. pass
  22.  
  23. def __contains__(self, *args, **kwargs): # real signature unknown
  24. """ Return key in self. """
  25. pass
  26.  
  27. def __eq__(self, *args, **kwargs): # real signature unknown
  28. """ Return self==value. """
  29. pass
  30.  
  31. def __getattribute__(self, *args, **kwargs): # real signature unknown
  32. """ Return getattr(self, name). """
  33. pass
  34.  
  35. def __getitem__(self, *args, **kwargs): # real signature unknown
  36. """ Return self[key]. """
  37. pass
  38.  
  39. def __getnewargs__(self, *args, **kwargs): # real signature unknown
  40. pass
  41.  
  42. def __ge__(self, *args, **kwargs): # real signature unknown
  43. """ Return self>=value. """
  44. pass
  45.  
  46. def __gt__(self, *args, **kwargs): # real signature unknown
  47. """ Return self>value. """
  48. pass
  49.  
  50. def __hash__(self, *args, **kwargs): # real signature unknown
  51. """ Return hash(self). """
  52. pass
  53.  
  54. def __init__(self, seq=()): # known special case of tuple.__init__
  55. """
  56. tuple() -> empty tuple
  57. tuple(iterable) -> tuple initialized from iterable's items
  58.  
  59. If the argument is a tuple, the return value is the same object.
  60. # (copied from class doc)
  61. """
  62. pass
  63.  
  64. def __iter__(self, *args, **kwargs): # real signature unknown
  65. """ Implement iter(self). """
  66. pass
  67.  
  68. def __len__(self, *args, **kwargs): # real signature unknown
  69. """ Return len(self). """
  70. pass
  71.  
  72. def __le__(self, *args, **kwargs): # real signature unknown
  73. """ Return self<=value. """
  74. pass
  75.  
  76. def __lt__(self, *args, **kwargs): # real signature unknown
  77. """ Return self<value. """
  78. pass
  79.  
  80. def __mul__(self, *args, **kwargs): # real signature unknown
  81. """ Return self*value.n """
  82. pass
  83.  
  84. @staticmethod # known case of __new__
  85. def __new__(*args, **kwargs): # real signature unknown
  86. """ Create and return a new object. See help(type) for accurate signature. """
  87. pass
  88.  
  89. def __ne__(self, *args, **kwargs): # real signature unknown
  90. """ Return self!=value. """
  91. pass
  92.  
  93. def __repr__(self, *args, **kwargs): # real signature unknown
  94. """ Return repr(self). """
  95. pass
  96.  
  97. def __rmul__(self, *args, **kwargs): # real signature unknown
  98. """ Return self*value. """
  99. pass

示例:

  1. ############### 元组 #################
  2. name_tuple = ('alex', 'eric')
  3. # 索引
  4. print(name_tuple[0])
  5. # len
  6. print(name_tuple[len(name_tuple)-1])
  7. # 切片
  8. print(name_tuple[0:1])
  9. # for
  10. for i in name_tuple:
  11. print(i)
  12. # 删除
  13. # del name_tuple[0] 不支持
  14. # count,计算元素出现的个数
  15. print(name_tuple.count('alex'))
  16. # index 获取指定元素的索引位置
  17. print(name_tuple.index('alex'))

示例练习:

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. # tuple元祖的特殊方法练习
  4. name_list = ('alex', 'seven', 'eric', "alex")
  5. print(name_list.index("alex")) # 获取指定元素的索引编号
  6. print(name_list.count("alex")) # 获取指定元素的个数
  7.  
  8. # tuple(列表)列表变元组
  9. a = range(10)
  10. print(a) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  11. d = tuple(a)
  12. print(d) # (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
  13. # list(元组)元组变列表
  14. print(d) # (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
  15. e = list(a)
  16. print(e) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  17.  
  18. #有些时候我们的列表数据不想被人修改时怎么办? 就可以用元组存放,元组又被称为只读列表,不能修改。
  19. # 定义:与列表类似,只不过[]改成(),很多用法和list一致,
  20.  
  21. # 注意:元组本身不可变,如果元组中还包含其他可变元素,这些可变元素可以改变
  22.  
  23. data = (99, 88, 77, ['Alex', 'Jack'], 33)
  24. data[3][0] = '金角大王'
  25. print(data) # (99, 88, 77, ['金角大王', 'Jack'], 33)
  26. # 为啥呢? 因为元组只是存每个元素的内存地址,上面[‘金角大王’, ‘Jack’]这个列表本身的内存地址存在元组里确实不可变,但是这个列表包含的元素的内存地址是存在另外一块空间里的,是可变的。

6、字典(无序)

创建字典:

创建字典,字典的每一个元素,键值对。内部没有排序。
  1. user_info={"name":"alex",
  2. "age":18,
  3. "gender":"M",
  4. }
a=dict()#可以接收空参数,创建空字典,可以接收一个键值对(k1=123,k2=333),可以接收一个可迭代的东西,接收列表的时候,使用enumerate
  1. li=["kk","jkjkj","sdfj"]
  2. new_dict=dict(enumerate(li))
  3. print new_dict #{0: 'kk', 1: 'jkjkj', 2: 'sdfj'}
  1.  
  1. 创建操作
  2.  
  3. >>>person = {"name": "alex", 'age': 20}
  4. #或
  5. >>>person = dict(name='seven', age=20)
  6. #或
  7. >>>person = dict({"name": "egon", 'age': 20})
  8. #或
  9. >>> {}.fromkeys([1,2,3,4,5,6,7,8],100)
  10. {1: 100, 2: 100, 3: 100, 4: 100, 5: 100, 6: 100, 7: 100, 8: 100}
  11. 增加操作
  12.  
  13. names = {
  14. "alex": [23, "CEO", 66000],
  15. "黑姑娘": [24, "行政", 4000],
  16. }
  17. # 新增k
  18. names["佩奇"] = [26, "讲师", 40000]
  19. names.setdefault("oldboy",[50,"boss",100000]) # D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
  20. 删除操作
  21.  
  22. names.pop("alex") # 删除指定key
  23. names.popitem() # 随便删除1个key
  24. del names["oldboy"] # 删除指定key,同pop方法
  25. names.clear() # 清空dict
  26. 修改操作
  27.  
  28. dic['key'] = 'new_value',如果key在字典中存在,'new_value'将会替代原来的value值;
  29. dic.update(dic2) 将字典dic2的键值对添加到字典dic中,如果有重复的key,这更新value
  30. 查操作
  31.  
  32. dic['key'] #返回字典中key对应的值,若key不存在字典中,则报错;
  33. dic.get(key, default = None)#返回字典中key对应的值,若key不存在字典中,则返回default的值(default默认为None
  34. 'key' in dic #若存在则返回True,没有则返回False
  35. dic.keys() 返回一个包含字典所有KEY的列表;
  36. dic.values() 返回一个包含字典所有value的列表;
  37. dic.items() 返回一个包含所有(键,值)元组的列表;
  38. 循环
  39.  
  40. 1for k in dic.keys()
  41. 2for k,v in dic.items()
  42. 3for k in dic # 推荐用这种,效率速度最快
  43. info = {
  44. "name":"小猿圈",
  45. "mission": "帮一千万极客高效学编程",
  46. "website": "http://apeland.com"
  47. }
  48. for k in info:
  49. print(k,info[k])
  50. 输出
  51. name 小猿圈
  52. mission 帮一千万极客高效学编程
  53. website http://apeland.com
  54. 求长度
  55.  
  56. len(dic)
  1.  

常用操作:

  • 索引

    • print user_info["name"]
      print user_info["age"]
  • 新增
    • 直接添加user_info["新的键"]="新的值"
    • user_info.update({"kkk":"xxx"})
  • 删除
    • pop
  • 键、值、键值对
  • 循环
      1. for item in user_info: #默认输出的是keys
      2. print item
      3. for item in user_info.values: #获取所有的值
      4. print item
      5. for i j in user_info.items: #获取所有的键值对
      6. print i,j
      7. user_info.keys() #获取所有的key
      8. user_info.values() #获取所有的值
      9. user_info.items() #获取所有的键值对
  • 长度
    • len(user_info)
  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. """ 浅拷贝 D.copy() -> a shallow copy of D """
  19. pass
  20.  
  21. @staticmethod # known case
  22. def fromkeys(*args, **kwargs): # real signature unknown
  23. """ Returns a new dict with keys from iterable and values equal to value. """
  24. pass
  25.  
  26. def get(self, k, d=None): # real signature unknown; restored from __doc__
  27. """ 根据key获取 d是默认是 为 None D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """
  28. pass
  29.  
  30. def items(self): # real signature unknown; restored from __doc__
  31. """ 将字典的key value都打印成列表元组 D.items() -> a set-like object providing a view on D's items """
  32. pass
  33.  
  34. def keys(self): # real signature unknown; restored from __doc__
  35. """打印字典的key D.keys() -> a set-like object providing a view on D's keys """
  36. pass
  37.  
  38. def pop(self, k, d=None): # real signature unknown; restored from __doc__
  39. """ 获取并在字典中移除
  40. D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
  41. If key is not found, d is returned if given, otherwise KeyError is raised
  42. """
  43. pass
  44.  
  45. def popitem(self): # real signature unknown; restored from __doc__
  46. """ 获取并在列表中移除
  47. D.popitem() -> (k, v), remove and return some (key, value) pair as a
  48. 2-tuple; but raise KeyError if D is empty.
  49. """
  50. pass
  51.  
  52. def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
  53. """如果key不存在,则创建,如果存在,则返回已存在的值且不修改
  54.  
  55.    D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
  56. pass
  57.  
  58. def update(self, E=None, **F): # known special case of dict.update
  59. """
  60. D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
  61. If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
  62. If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
  63. In either case, this is followed by: for k in F: D[k] = F[k]
  64. """
  65. pass
  66.  
  67. def values(self): # real signature unknown; restored from __doc__
  68. """ 所有的值 D.values() -> an object providing a view on D's values """
  69. pass
  70.  
  71. def __contains__(self, *args, **kwargs): # real signature unknown
  72. """ True if D has a key k, else False. """
  73. pass
  74.  
  75. def __delitem__(self, *args, **kwargs): # real signature unknown
  76. """ Delete self[key]. """
  77. pass
  78.  
  79. def __eq__(self, *args, **kwargs): # real signature unknown
  80. """ Return self==value. """
  81. pass
  82.  
  83. def __getattribute__(self, *args, **kwargs): # real signature unknown
  84. """ Return getattr(self, name). """
  85. pass
  86.  
  87. def __getitem__(self, y): # real signature unknown; restored from __doc__
  88. """ x.__getitem__(y) <==> x[y] """
  89. pass
  90.  
  91. def __ge__(self, *args, **kwargs): # real signature unknown
  92. """ Return self>=value. """
  93. pass
  94.  
  95. def __gt__(self, *args, **kwargs): # real signature unknown
  96. """ Return self>value. """
  97. pass
  98.  
  99. def __init__(self, seq=None, **kwargs): # known special case of dict.__init__
  100. """
  101. dict() -> new empty dictionary
  102. dict(mapping) -> new dictionary initialized from a mapping object's
  103. (key, value) pairs
  104. dict(iterable) -> new dictionary initialized as if via:
  105. d = {}
  106. for k, v in iterable:
  107. d[k] = v
  108. dict(**kwargs) -> new dictionary initialized with the name=value pairs
  109. in the keyword argument list. For example: dict(one=1, two=2)
  110. # (copied from class doc)
  111. """
  112. pass
  113.  
  114. def __iter__(self, *args, **kwargs): # real signature unknown
  115. """ Implement iter(self). """
  116. pass
  117.  
  118. def __len__(self, *args, **kwargs): # real signature unknown
  119. """ Return len(self). """
  120. pass
  121.  
  122. def __le__(self, *args, **kwargs): # real signature unknown
  123. """ Return self<=value. """
  124. pass
  125.  
  126. def __lt__(self, *args, **kwargs): # real signature unknown
  127. """ Return self<value. """
  128. pass
  129.  
  130. @staticmethod # known case of __new__
  131. def __new__(*args, **kwargs): # real signature unknown
  132. """ Create and return a new object. See help(type) for accurate signature. """
  133. pass
  134.  
  135. def __ne__(self, *args, **kwargs): # real signature unknown
  136. """ Return self!=value. """
  137. pass
  138.  
  139. def __repr__(self, *args, **kwargs): # real signature unknown
  140. """ Return repr(self). """
  141. pass
  142.  
  143. def __setitem__(self, *args, **kwargs): # real signature unknown
  144. """ Set self[key] to value. """
  145. pass
  146.  
  147. def __sizeof__(self): # real signature unknown; restored from __doc__
  148. """ D.__sizeof__() -> size of D in memory, in bytes """
  149. pass
  150.  
  151. __hash__ = None

示例:

  1. #!/usr/bin/env python
  2. # _*_ coding:utf-8 _*_
  3.  
  4. dic={1:2,"alex":4,4:9}
  5. print(dic.get("alex"))
  6. print(dic.items())
  7. print(dic.keys())
  8. print(dic.values())
  9. print(dic.pop(2,None))
  10. print(dic.setdefault("name","rain"))
  11.  
  12. ###################### 字典 ###################
  13. # 字典的每一个元素,键值对
  14. user_info = {
  15. 0: "alex",
  16. "age": 73,
  17. 2: 'M'
  18. }
  19. # 0 “alex"
  20. # 1 73
  21.  
  22. # 索引
  23. # print(user_info[0])
  24. # print(user_info["age"])
  25.  
  26. # 循环,默认值输出key
  27. # for i in user_info:
  28. # print(i)
  29.  
  30. # # 获取所有键
  31. # print(user_info.keys())
  32. # # 获取所有值
  33. # print(user_info.values())
  34. # # 获取所有键值对
  35. # print(user_info.items())
  36.  
  37. # for i in user_info.keys():
  38. # print(i)
  39. #
  40. # for i in user_info.values():
  41. # print(i)
  42.  
  43. # user_info = {
  44. # 0: "alex",
  45. # "age": 73,
  46. # 2: 'M'
  47. # }
  48. # for k,v in user_info.items():
  49. # print(k)
  50. # print(v)
  51.  
  52. # clear,清除所有内容
  53. # user_info.clear()
  54. # print(user_info)
  55.  
  56. # get 根据key获取值,如果key不存在,可以指定一个默认值
  57. # val = user_info.get('age')
  58. # print(val)
  59. # val = user_info.get('age', '123')
  60. # print(val)
  61. # 索引取值时,key不存在,报错
  62. # print(user_info['age'])
  63. # print(user_info['age1111'])
  64.  
  65. # has_key 检查字典中指定key是否存在 3版本python没有了 可以用in 判断
  66. # ret = 'agfffe' in user_info.keys()
  67. # print(ret)
  68. # pop
  69.  
  70. # popitem
  71.  
  72. # update
  73. # print(user_info)
  74. # test = {
  75. # "a1": 123,
  76. # 'a2': 456
  77. # }
  78. # user_info.update(test)
  79. # print(user_info)
  80.  
  81. # 删除指定索引的键值对
  82. test = {
  83. "a1": 123,
  84. 'a2': 456
  85. }
  86.  
  87. del test['a1']
  88. print(test)

示例练习:

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. #dict字典的特殊方法
  4.  
  5. user_info={"name":"alex",
  6. "age":18,
  7. "gender":"M"
  8. }
  9. print len(user_info)#长度
  10. #user_info.clear()#清空字典,清楚所有内容
  11. print user_info.get("name")
  12. print user_info.get("name1",123) # """ 根据key获取值,d是默认值 """如果key不存在,返回默认值,不会报错
  13. print user_info["name"] #如果不存在会报错
  14. print user_info.has_key("name") #""" 是否有key """
  15. a=user_info.pop("age")#获取并在字典中移除,可以将key赋值给一个变量
  16. print user_info,a
  17. a=user_info.popitem()#移除key values 赋值给一个元祖中
  18. print user_info,
  19.  
  20. user_info.iteritems()
  21. print user_info
  22. user_info.update({"kkk":"jjk"})#更新
  23. print user_info
  24.  
  25. #@staticmethod,类方法
  26. user_info_new=dict.fromkeys(["k","name"],"alex")
  27. print user_info_new
  1. 2版本python 查看字典有没有这个key
  2. >>> contact['']
  3. Traceback (most recent call last):
  4. File "<stdin>", line 1, in <module>
  5. KeyError: ''
  6. >>> contact.has_key('')
  7. False
  8. >>> contact.has_key('')
  9. True
  10. 清空字典contact.clear()
  11. >>> contact.clear()

5、for循环

1、for循环
用户按照顺序循环可迭代对象中的内容,
PS:break、continue
  1. li = [11,22,33]
  2. for i in li:
  3. print(li.index(i),i)

6、enumrate 

为可迭代的对象添加序号

  1. li = [11,22,33]
  2. for k,v in enumerate(li, 1):
  3. print(k,v)

7、range 和xrange

迭代循环
xrange不会先在内存中创建,而是每次循环就创建一次。节约内存。
3版本python只有range了,等同于xrange
 
  1. print range(1, 10)
  2. # 结果:[1, 2, 3, 4, 5, 6, 7, 8, 9]
  3.  
  4. print range(1, 10, 2)
  5. # 结果:[1, 3, 5, 7, 9]
  6.  
  7. print range(30, 0, -2)
  8. # 结果:[30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2]
  9.  
  10. 例如
  11. print(range(1,10))
  12.   没有循环,因此输出 range(1, 10) 而不是1 2 3.。。10
  13.   

8、练习题

1、元素分类

有如下值集合 [11,22,33,44,55,66,77,88,99,90],将所有大于 66 的值保存至字典的第一个key中,将小于等于 66 的值保存至第二个key的值中。
即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. lis=[11,22,33,44,55,66,77,88,99,90]
  4. dic={"k1":[],"k2":[]}
  5. for i in lis:
  6. if i>66:
  7. dic["k1"].append(i)
  8. else:
  9. dic["k2"].append(i)
  10. print dic
2、查找
查找列表中元素,移动空格,并查找以 a或A开头 并且以 c 结尾的所有元素。
    li = ["alec", " aric", "Alex", "Tony", "rain"]
    tu = ("alec", " aric", "Alex", "Tony", "rain") 
    dic = {'k1': "alex", 'k2': ' aric',  "k3": "Alex", "k4": "Tony"}
  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. li = ["alec", " Aric", "Alei", "Tony", "rain"]
  4. tu = ("alec", " Aric", "Alei", "Tony", "rain")
  5. dic = {'k1': "alei", 'k2': ' aric', "k3": "Alec", "k4": "Tony"}
  6. li_new = []
  7. tu_new = []
  8. dic_new={}
  9. for i in li:
  10. i=i.strip()
  11. #if判断顺序,从前往后,or,自己成功就行了,and。
  12. if (i.startswith("a") or i.startswith("A")) and i.endswith("c"):
  13. li_new.append(i)
  14. else:
  15. pass
  16. for i in tu:
  17. i=i.strip()
  18. if (i.startswith("a") or i.startswith("A")) and i.endswith("c"):
  19. tu_new.append(i)
  20. else:
  21. pass
  22. for i,j in dic.items():
  23. j=j.strip()
  24. if (j.startswith("a") or j.startswith("A")) and j.endswith("c"):
  25. # dic_new.update({i:j})
  26. dic_new[i]=j
  27. else:
  28. pass
  29. print li_new
  30. print tu_new
  31. print dic_new 
3、输出商品列表,用户输入序号,显示用户选中的商品  利用 enumrate
    商品 li = ["手机", "电脑", '鼠标垫', '游艇']

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. li=["手机", "电脑", '鼠标垫', '游艇']
  4. for i,j in enumerate(li,1):
  5. print i,j
  6. inp=int(raw_input("请选择:"))
  7. print li[inp-1]
4、购物车

功能要求:

  • 要求用户输入总资产,例如:2000
  • 显示商品列表,让用户根据序号选择商品,加入购物车
  • 购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。
  • 附加:可充值、某商品移除购物车
  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. goods = [
  4. {"name": "电脑", "price": 1999},
  5. {"name": "鼠标", "price": 10},
  6. {"name": "游艇", "price": 20},
  7. {"name": "美女", "price": 998},
  8. ]
  9. glod=int(input("您的总资产为:"))
  10. def show_goods():
  11. for i in goods:
  12. print(str(goods.index(i)) + ":" + i["name"], i["price"], "元")
  13. print("4:结算")
  14. def show_gwc():
  15. for item in gwc.items():
  16. print(item[0], "数量:" + str(item[1]["数量"]), "单价:" + str(item[1]["单价"]))
  17. total=0
  18. gwc={}
  19. show_goods()
  20. while True:
  21. get_goods=int(input("请输入你要购买的商品编号,结算请输入4:"))
  22. if get_goods<3:
  23. if goods[get_goods]["name"] in gwc.keys():
  24. gwc[goods[get_goods]["name"]]["数量"]+=1
  25. else:
  26. gwc[goods[get_goods]["name"]] = {"数量": 1, "单价": goods[get_goods]["price"]}
  27. total = total + goods[get_goods]["price"]
  28. show_gwc()
  29. show_goods()
  30. continue
  31. elif get_goods>4:
  32. print("输入错误")
  33. show_goods()
  34. continue
  35. else:
  36. if total<=glod:
  37. print("你购买的商品总额为%d元,购买成功" % total)
  38. else:
  39. print("余额不足")
  40. break

python基础-2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange的更多相关文章

  1. Python基础-字符编码与转码

    ***了解计算机的底层原理*** Python全栈开发之Python基础-字符编码与转码 需知: 1.在python2默认编码是ASCII, python3里默认是utf-8 2.unicode 分为 ...

  2. python基础之编码问题

    python基础之编码问题 本节内容 字符串编码问题由来 字符串编码解决方案 1.字符串编码问题由来 由于字符串编码是从ascii--->unicode--->utf-8(utf-16和u ...

  3. 第三篇:python基础之编码问题

    python基础之编码问题   python基础之编码问题 本节内容 字符串编码问题由来 字符串编码解决方案 1.字符串编码问题由来 由于字符串编码是从ascii--->unicode---&g ...

  4. python基础之打/解包及运算符与控制流程

    python基础之打/解包及运算符与控制流程 python中的解压缩(即序列类型的打包和解包) python提供了两个设计元祖和其他序列类型的处理的便利,也就是自动打包与自动解包功能,比如: data ...

  5. python基础(5):格式化输出、基本运算符、编码问题

    1. 格式化输出 现在有以下需求,让⽤户输入name, age, job,hobby 然后输出如下所⽰: ------------ info of Alex Li ----------- Name : ...

  6. 2.Python基础认识(格式化输出,while语句,运算符,编码,单位转化)

    Python基础认识 1.字符串的格式化初识及占位符的简单应用 字符串的格式化 按照既定的要求进行有规定排版的一种输出方式. #我们想要输出的格式如下: ----------------------- ...

  7. Python基础二. 数据结构、控制流、运算符、真值测试

    一.概述 数据结构上广义上有两种,单一类型和集合类型 单一类型,表示一种对象 集合类型,表示包含多种对象 Python 中的内建的数据类型有str.list.tuple.dict.set.number ...

  8. Python基础学习笔记(三)运算符

    参考资料: 1. <Python基础教程> 2. http://www.runoob.com/python/python-chinese-encoding.html 3. http://w ...

  9. 小话python 中的编码转换

    1.前言: 一直认为自己会了,也明白了其中的知识,但是过几天不用就马上忘记了,总不能天天复习吧!还是来个好记性不如烂笔头吧! 2.编码: python解释器在加载 .py 文件中的代码时,会对内容进行 ...

随机推荐

  1. Beta冲刺-(2/3)

    这个作业属于哪个课程 https://edu.cnblogs.com/campus/xnsy/SoftwareEngineeringClass1/ 这个作业要求在哪里 https://edu.cnbl ...

  2. python3-获取对象信息

    当我们拿到一个对象的引用时,如何知道这个对象是什么类型.有哪些方法呢? 使用type() 首先,我们来判断对象类型,使用type()函数: 基本类型都可以用type()判断: >>> ...

  3. Centos7没有Ifconfig命令该怎么办?

    centos7没有ifconfig命令该怎么办? linux系统查看ip地址常用命令是[ifconfig],CentOS 7.0最小安装是没有ifconfig命令怎么办?当然可用[ip addr]查看 ...

  4. MySQL数据库3分组与单表、多表查询

    目录 一.表操作的补充 1.1null 和 not null 1.2使用not null的时候 二.单表的操作(import) 2.1分组 2.1.1聚合函数 2.1.2group by 2.1.3h ...

  5. 花式赋值、列表、字典、解压缩、input()、格式化学习笔记

    目录 花式赋值 列表(list) 字典(dict) 解压缩 input()与用户交互 格式化的三种方式 f_String格式化(important) %s.%d占位符 format 格式化(不常用) ...

  6. 【leetcode】1143. Longest Common Subsequence

    题目如下: Given two strings text1 and text2, return the length of their longest common subsequence. A su ...

  7. SonarQube规则之坏味道类型

    1.Abbreviation As Word In Name (默认 关闭)坏味道 主要检查验证标识符名称中的缩写(连续大写字母)长度,还允许执行骆驼案例命名allowedAbbreviationLe ...

  8. linux运维、架构之路-MySQL备份与恢复(四)

    一.备份方式 ①逻辑备份(文件表示:SQL语句) ②物理备份(数据文件的二进制副本) ③基于快照的备份 ④基于复制的备份 二.备份工具 ①mysqldump:原生自带的逻辑备份工具 ②mysqlbin ...

  9. lua脚本入门

    在网上下载一些工程,里边常常存在.lua .sh .in .cmake .bat等文件 今天专门查了一下相关文件的作用 .sh 通常是linux.unix系统下的脚本文件(文本文件),用于调用默认的s ...

  10. 配置 app.js 文件

    pp.js 中存放全局的 JavaScript 逻辑. 示例: App({ onLaunch: function () { console.log('SWAN launch'); }, onShow: ...