1、编码转换
unicode 可以编译成 UTF-U GBK
即
#!/usr/bin/env python
# -*- coding:utf-8 -*-
a = '测试字符' #默认是utf-8
a_unicode = a.decode('utf-8') # decode是解码成unicode 括号是脚本内容的默认编码 即:将脚本内容的utf-8解码成unicode
a_gbk = a_unicode.encode('gbk') #encode是编码,将unicode的编码内容编码成指定的,这里是gbk
print(a_gbk) #用于终端打印
print(u"测试字符二") #3里面是字符串 2里面是unicode #3版本直接将utf-8编码成GBK 不需要先转成unicode了
2、pycharm的基本配置
1、file-setings-editor- file && file encode template Python Script输入 以下内容作为声明模板
#!/usr/bin/env python
# _*_ 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),来查看
int(整型)
在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807
class int(object):
"""
int(x=0) -> int or long
int(x, base=10) -> int or long Convert a number or string to an integer, or return 0 if no arguments
are given. If x is floating point, the conversion truncates towards zero.
If x is outside the integer range, the function returns a long instead. If x is not a number or if base is given, then x must be a string or
Unicode object representing an integer literal in the given base. The
literal can be preceded by '+' or '-' and be surrounded by whitespace.
The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to
interpret the base from the string as an integer literal.
>>> int('0b100', base=0)
"""
def bit_length(self):
""" 返回表示该数字的时占用的最少位数 """
"""
int.bit_length() -> int Number of bits necessary to represent self in binary.
>>> bin(37)
'0b100101'
>>> (37).bit_length()
"""
return 0 def conjugate(self, *args, **kwargs): # real signature unknown
""" 返回该复数的共轭复数 """
""" Returns self, the complex conjugate of any int. """
pass def __abs__(self):
""" 返回绝对值 """
""" x.__abs__() <==> abs(x) """
pass def __add__(self, y):
""" x.__add__(y) <==> x+y """
pass def __and__(self, y):
""" x.__and__(y) <==> x&y """
pass def __cmp__(self, y):
""" 比较两个数大小 """
""" x.__cmp__(y) <==> cmp(x,y) """
pass def __coerce__(self, y):
""" 强制生成一个元组 """
""" x.__coerce__(y) <==> coerce(x, y) """
pass def __divmod__(self, y):
""" 相除,得到商和余数组成的元组 """
""" x.__divmod__(y) <==> divmod(x, y) """
pass def __div__(self, y):
""" x.__div__(y) <==> x/y """
pass def __float__(self):
""" 转换为浮点类型 """
""" x.__float__() <==> float(x) """
pass def __floordiv__(self, y):
""" x.__floordiv__(y) <==> x//y """
pass def __format__(self, *args, **kwargs): # real signature unknown
pass def __getattribute__(self, name):
""" x.__getattribute__('name') <==> x.name """
pass def __getnewargs__(self, *args, **kwargs): # real signature unknown
""" 内部调用 __new__方法或创建对象时传入参数使用 """
pass def __hash__(self):
"""如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等。"""
""" x.__hash__() <==> hash(x) """
pass def __hex__(self):
""" 返回当前数的 十六进制 表示 """
""" x.__hex__() <==> hex(x) """
pass def __index__(self):
""" 用于切片,数字无意义 """
""" x[y:z] <==> x[y.__index__():z.__index__()] """
pass def __init__(self, x, base=10): # known special case of int.__init__
""" 构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略 """
"""
int(x=0) -> int or long
int(x, base=10) -> int or long Convert a number or string to an integer, or return 0 if no arguments
are given. If x is floating point, the conversion truncates towards zero.
If x is outside the integer range, the function returns a long instead. If x is not a number or if base is given, then x must be a string or
Unicode object representing an integer literal in the given base. The
literal can be preceded by '+' or '-' and be surrounded by whitespace.
The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to
interpret the base from the string as an integer literal.
>>> int('0b100', base=0)
# (copied from class doc)
"""
pass def __int__(self):
""" 转换为整数 """
""" x.__int__() <==> int(x) """
pass def __invert__(self):
""" x.__invert__() <==> ~x """
pass def __long__(self):
""" 转换为长整数 """
""" x.__long__() <==> long(x) """
pass def __lshift__(self, y):
""" x.__lshift__(y) <==> x<<y """
pass def __mod__(self, y):
""" x.__mod__(y) <==> x%y """
pass def __mul__(self, y):
""" x.__mul__(y) <==> x*y """
pass def __neg__(self):
""" x.__neg__() <==> -x """
pass @staticmethod # known case of __new__
def __new__(S, *more):
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass def __nonzero__(self):
""" x.__nonzero__() <==> x != 0 """
pass def __oct__(self):
""" 返回改值的 八进制 表示 """
""" x.__oct__() <==> oct(x) """
pass def __or__(self, y):
""" x.__or__(y) <==> x|y """
pass def __pos__(self):
""" x.__pos__() <==> +x """
pass def __pow__(self, y, z=None):
""" 幂,次方 """
""" x.__pow__(y[, z]) <==> pow(x, y[, z]) """
pass def __radd__(self, y):
""" x.__radd__(y) <==> y+x """
pass def __rand__(self, y):
""" x.__rand__(y) <==> y&x """
pass def __rdivmod__(self, y):
""" x.__rdivmod__(y) <==> divmod(y, x) """
pass def __rdiv__(self, y):
""" x.__rdiv__(y) <==> y/x """
pass def __repr__(self):
"""转化为解释器可读取的形式 """
""" x.__repr__() <==> repr(x) """
pass def __str__(self):
"""转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式"""
""" x.__str__() <==> str(x) """
pass def __rfloordiv__(self, y):
""" x.__rfloordiv__(y) <==> y//x """
pass def __rlshift__(self, y):
""" x.__rlshift__(y) <==> y<<x """
pass def __rmod__(self, y):
""" x.__rmod__(y) <==> y%x """
pass def __rmul__(self, y):
""" x.__rmul__(y) <==> y*x """
pass def __ror__(self, y):
""" x.__ror__(y) <==> y|x """
pass def __rpow__(self, x, z=None):
""" y.__rpow__(x[, z]) <==> pow(x, y[, z]) """
pass def __rrshift__(self, y):
""" x.__rrshift__(y) <==> y>>x """
pass def __rshift__(self, y):
""" x.__rshift__(y) <==> x>>y """
pass def __rsub__(self, y):
""" x.__rsub__(y) <==> y-x """
pass def __rtruediv__(self, y):
""" x.__rtruediv__(y) <==> y/x """
pass def __rxor__(self, y):
""" x.__rxor__(y) <==> y^x """
pass def __sub__(self, y):
""" x.__sub__(y) <==> x-y """
pass def __truediv__(self, y):
""" x.__truediv__(y) <==> x/y """
pass def __trunc__(self, *args, **kwargs):
""" 返回数值被截取为整形的值,在整形中无意义 """
pass def __xor__(self, y):
""" x.__xor__(y) <==> x^y """
pass denominator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
""" 分母 = 1 """
"""the denominator of a rational number in lowest terms""" imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
""" 虚数,无意义 """
"""the imaginary part of a complex number""" numerator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
""" 分子 = 数字大小 """
"""the numerator of a rational number in lowest terms""" real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
""" 实属,无意义 """
"""the real part of a complex number""" int
"hello world"
字符串格式化
name = "alex"
print "i am %s " % name #输出: 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就是反向。
-
class str(object):
"""
str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str Create a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.__str__() (if defined)
or repr(object).
encoding defaults to sys.getdefaultencoding().
errors defaults to 'strict'.
"""
def capitalize(self): # real signature unknown; restored from __doc__
""" #将 字符串首字母 小写改大写
S.capitalize() -> str Return a capitalized version of S, i.e. make the first character
have upper case and the rest lower case. """
return "" def casefold(self): # real signature unknown; restored from __doc__
"""
S.casefold() -> str Return a version of S suitable for caseless comparisons.
"""
return "" def center(self, width, fillchar=None): # real signature unknown; restored from __doc__
""" 可以为字符串 填充自定字符 长度=字符+指定字符
S.center(width[, fillchar]) -> str Return S centered in a string of length width. Padding is
done using the specified fill character (default is a space)
"""
return "" def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
""" 下面是详细参数:
子串:是要搜索的子串。 开始:从该指数开始搜索。第一个字符从索引0开始。通过默认搜索引擎从索引0开始。 结束:搜索从该指数结束。第一个字符从索引0开始。默认情况下,搜索结束,在最后一个索引。 S.count(sub[, start[, end]]) -> int Return the number of non-overlapping occurrences of substring sub in
string S[start:end]. Optional arguments start and end are
interpreted as in slice notation.
"""
return 0 def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__
""" 编码 上面有介绍
S.encode(encoding='utf-8', errors='strict') -> bytes Encode S using the codec registered for encoding. Default encoding
is 'utf-8'. errors may be given to set a different error
handling scheme. Default is 'strict' meaning that encoding errors raise
a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
'xmlcharrefreplace' as well as any other name registered with
codecs.register_error that can handle UnicodeEncodeErrors.
"""
return b"" def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
""" 以 某个字符结束
suffix -- 该参数可以是一个字符串或者是一个元素。 start -- 字符串中的开始位置。 end -- 字符中结束位置。 返回值 如果字符串含有指定的后缀返回True,否则返回False。 S.endswith(suffix[, start[, end]]) -> bool Return True if S ends with the specified suffix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
suffix can also be a tuple of strings to try.
"""
return False def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__
""" 把tab转换成空格
S.expandtabs(tabsize=8) -> str Return a copy of S where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
"""
return "" def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
"""
find(str, pos_start, pos_end) 解释: str:被查找“字串” pos_start:查找的首字母位置(从0开始计数。默认:0) pos_end: 查找的末尾位置(默认-1) 返回值:如果查到:返回查找的第一个出现的位置。否则,返回-1。 S.find(sub[, start[, end]]) -> int Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation. Return -1 on failure.
"""
return 0 def format(*args, **kwargs): # known special case of str.format
""" 占位符 类似变量引用
s = "print hell {0} ,age {1}"
print(s.format('alex',19)) S.format(*args, **kwargs) -> str Return a formatted version of S, using substitutions from args and kwargs.
The substitutions are identified by braces ('{' and '}').
"""
pass def format_map(self, mapping): # real signature unknown; restored from __doc__
"""字符串格式化,动态参数,将函数式编程时细说
S.format_map(mapping) -> str Return a formatted version of S, using substitutions from mapping.
The substitutions are identified by braces ('{' and '}').
"""
return "" def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
""" #跟find类似但是 没有找到的话会报错。 而find是返回-1
S.index(sub[, start[, end]]) -> int Like S.find() but raise ValueError when the substring is not found.
"""
return 0 def isalnum(self): # real signature unknown; restored from __doc__
""" #判断是否是数字和字母
S.isalnum() -> bool Return True if all characters in S are alphanumeric
and there is at least one character in S, False otherwise.
"""
return False def isalpha(self): # real signature unknown; restored from __doc__
"""是否是字母
S.isalpha() -> bool Return True if all characters in S are alphabetic
and there is at least one character in S, False otherwise.
"""
return False def isdecimal(self): # real signature unknown; restored from __doc__
"""
S.isdecimal() -> bool Return True if there are only decimal characters in S,
False otherwise.
"""
return False def isdigit(self): # real signature unknown; restored from __doc__
""" 是否是数字
S.isdigit() -> bool Return True if all characters in S are digits
and there is at least one character in S, False otherwise.
"""
return False def isidentifier(self): # real signature unknown; restored from __doc__
"""
S.isidentifier() -> bool Return True if S is a valid identifier according
to the language definition. Use keyword.iskeyword() to test for reserved identifiers
such as "def" and "class".
"""
return False def islower(self): # real signature unknown; restored from __doc__
"""是否小写字母
S.islower() -> bool Return True if all cased characters in S are lowercase and there is
at least one cased character in S, False otherwise.
"""
return False def isnumeric(self): # real signature unknown; restored from __doc__
"""
S.isnumeric() -> bool Return True if there are only numeric characters in S,
False otherwise.
"""
return False def isprintable(self): # real signature unknown; restored from __doc__
"""
S.isprintable() -> bool Return True if all characters in S are considered
printable in repr() or S is empty, False otherwise.
"""
return False def isspace(self): # real signature unknown; restored from __doc__
"""是否是空格
S.isspace() -> bool Return True if all characters in S are whitespace
and there is at least one character in S, False otherwise.
"""
return False def istitle(self): # real signature unknown; restored from __doc__
""" 是否是标题 字符串开头是大写 后面是小写
S.istitle() -> bool Return True if S is a titlecased string and there is at least one
character in S, i.e. upper- and titlecase characters may only
follow uncased characters and lowercase characters only cased ones.
Return False otherwise.
"""
return False def isupper(self): # real signature unknown; restored from __doc__
""" 是否是大写
S.isupper() -> bool Return True if all cased characters in S are uppercase and there is
at least one cased character in S, False otherwise.
"""
return False def join(self, iterable): # real signature unknown; restored from __doc__
""" 拼接 后面有例子 S.join(iterable) -> str Return a string which is the concatenation of the strings in the
iterable. The separator between elements is S.
"""
return "" def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__
""" 内容左对齐,右侧填充"""
"""
ljust()方法语法: str.ljust(width[, fillchar]) 参数 width -- 指定字符串长度。 fillchar -- 填充字符,默认为空格。 返回值 返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。 S.ljust(width[, fillchar]) -> str
Return S left-justified in a Unicode string of length width.Padding is done using the specified fill character (default is a space).
"""
return "" def lower(self): # real signature unknown; restored from __doc__
""" 转换为小写
S.lower() -> str
Return a copy of the string S converted to lowercase.
"""
return "" def lstrip(self, chars=None): # real signature unknown; restored from __doc__
""" 去除左侧开头空白
S.lstrip([chars]) -> str
Return a copy of the string S with leading whitespace removed. If chars is given and not None, remove characters in chars instead.
"""
return "" def maketrans(self, *args, **kwargs): # real signature unknown
""" 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.
"""
pass def partition(self, sep): # real signature unknown; restored from __doc__
""" 以指定 字符 开始分割 指定的字符也显示
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.
"""
pass
def replace(self, old, new, count=None): # real signature unknown; restored from __doc__
""" 替换
old -- 将被替换的子字符串。 new -- 新字符串,用于替换old子字符串。 max -- 可选字符串, 替换不超过 max 次 返回值 返回字符串中的 old(旧字符串) 替换成 new(新字符串)后生成的新字符串,如果指定第三个参数max,则替换不超过 max 次。 S.replace(old, new[, count]) -> str Return a copy of S with all occurrences of substring
old replaced by new. If the optional argument count is
given, only the first count occurrences are replaced.
"""
return "" def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
""" 从右开始查找
S.rfind(sub[, start[, end]]) -> int Return the highest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation. Return -1 on failure.
"""
return 0 def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
""" 顾名思义从右侧匹配
S.rindex(sub[, start[, end]]) -> int Like S.rfind() but raise ValueError when the substring is not found.
"""
return 0 def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__
""" 从右侧 填充
S.rjust(width[, fillchar]) -> str Return S right-justified in a string of length width. Padding is
done using the specified fill character (default is a space).
"""
return "" def rpartition(self, sep): # real signature unknown; restored from __doc__
""" 从右侧开始找到 分割 分割字符也显示
S.rpartition(sep) -> (head, sep, tail) Search for the separator sep in S, starting at the end of S, and return
the part before it, the separator itself, and the part after it. If the
separator is not found, return two empty strings and S.
"""
pass def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
""" 从右侧开始分割 sep是指定几个
S.rsplit(sep=None, maxsplit=-1) -> list of strings Return a list of the words in S, using sep as the
delimiter string, starting at the end of the string and
working to the front. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified, any whitespace string
is a separator.
"""
return [] def rstrip(self, chars=None): # real signature unknown; restored from __doc__
""" 从右侧 去除结尾的空格
S.rstrip([chars]) -> str Return a copy of the string S with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
"""
return "" def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
""" 分割 sep是几个算分割符
S.split(sep=None, maxsplit=-1) -> list of strings Return a list of the words in S, using sep as the
delimiter string. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified or is None, any
whitespace string is a separator and empty strings are
removed from the result.
"""
return [] def splitlines(self, keepends=None): # real signature unknown; restored from __doc__
"""
S.splitlines([keepends]) -> list of strings Return a list of the lines in S, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends
is given and true.
"""
return [] def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
""" 指定以什么开始
S.startswith(prefix[, start[, end]]) -> bool Return True if S starts with the specified prefix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
prefix can also be a tuple of strings to try.
"""
return False def strip(self, chars=None): # real signature unknown; restored from __doc__
""" 去除两端空格
S.strip([chars]) -> str Return a copy of the string S with leading and trailing
whitespace removed.
If chars is given and not None, remove characters in chars instead.
"""
return "" def swapcase(self): # real signature unknown; restored from __doc__
""" 大写转小写小写转大写
S.swapcase() -> str Return a copy of S with uppercase characters converted to lowercase
and vice versa.
"""
return "" def title(self): # real signature unknown; restored from __doc__
"""
S.title() -> str Return a titlecased version of S, i.e. words start with title case
characters, all remaining cased characters have lower case.
"""
return "" def translate(self, table): # real signature unknown; restored from __doc__
""" 转换,需要先做一个对应表,最后一个表示删除字符集合
intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)
str = "this is string example....wow!!!"print str.translate(trantab, 'xm') S.translate(table) -> str Return a copy of the string S in which each character has been mapped
through the given translation table. The table must implement
lookup/indexing via __getitem__, for instance a dictionary or list,
mapping Unicode ordinals to Unicode ordinals, strings, or None. If
this operation raises LookupError, the character is left untouched.
Characters mapped to None are deleted.
"""
return "" def upper(self): # real signature unknown; restored from __doc__
""" 大写显示
S.upper() -> str Return a copy of S converted to uppercase.
"""
return "" def zfill(self, width): # real signature unknown; restored from __doc__
""" 方法返回指定长度的字符串,原字符串右对齐,前面填充0。
S.zfill(width) -> str Pad a numeric string S with zeros on the left, to fill a field
of the specified width. The string S is never truncated.
"""
return "" def __add__(self, *args, **kwargs): # real signature unknown
""" Return self+value. """
pass def __contains__(self, *args, **kwargs): # real signature unknown
""" Return key in self. """
pass def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass def __format__(self, format_spec): # real signature unknown; restored from __doc__
"""
S.__format__(format_spec) -> str Return a formatted version of S as described by format_spec.
"""
return "" def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass def __getitem__(self, *args, **kwargs): # real signature unknown
""" Return self[key]. """
pass def __getnewargs__(self, *args, **kwargs): # real signature unknown
pass def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass def __hash__(self, *args, **kwargs): # real signature unknown
""" Return hash(self). """
pass def __init__(self, value='', encoding=None, errors='strict'): # known special case of str.__init__
"""
str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str Create a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.__str__() (if defined)
or repr(object).
encoding defaults to sys.getdefaultencoding().
errors defaults to 'strict'.
# (copied from class doc)
"""
pass def __iter__(self, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass def __len__(self, *args, **kwargs): # real signature unknown
""" Return len(self). """
pass def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass def __mod__(self, *args, **kwargs): # real signature unknown
""" Return self%value. """
pass def __mul__(self, *args, **kwargs): # real signature unknown
""" Return self*value.n """
pass @staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass def __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass def __rmod__(self, *args, **kwargs): # real signature unknown
""" Return value%self. """
pass def __rmul__(self, *args, **kwargs): # real signature unknown
""" Return self*value. """
pass def __sizeof__(self): # real signature unknown; restored from __doc__
""" S.__sizeof__() -> size of S in memory, in bytes """
pass def __str__(self, *args, **kwargs): # real signature unknown
""" Return str(self). """
pass
字符串练习
#!/usr/bin/env python
# -*- coding:utf-8 -*- # str字符串方法练习
a = "alex"
ret = a.capitalize() # 不用添加参数,字符串首字母变大写,str(object='') -> string
print(ret)
ret1 = a.center(20, "*") # 内容居中,width:总长度;fillchar:空白处填充内容,默认无。S.center(width[, fillchar]) -> string
print(ret1)
a2 = "alex is alph"
ret2 = a2.count("al") # 计算子序列个数,def count(self, sub, start=None, end=None):,可定义开始和结束位置。S.count(sub[, start[, end]]) -> int
ret3 = a2.count("a", 0)
print(ret2, ret3) ret4 = a2.endswith("alp", 0,-1) # """ 是否以 xxx 结束 """endswith(self, suffix, start=None, end=None):,可定义开始和结束的位置,S.endswith(suffix[, start[, end]]) -> bool
print(a2.startswith("a")) # """ 是否以 xxx 开始 """ startswith(self, prefix, start=None, end=None):,可定义开始和结束的位置,S.startswith(prefix[, start[, end]]) -> bool
print(ret4)
a3 = "hello\t999" # """ 将tab转换成空格,默认一个tab转换成8个空格 """def expandtabs(self, tabsize=None):可以定义空格个数,S.expandtabs([tabsize]) -> string
print(a3)
print(a3.expandtabs(20)) s = "hello alex"
s.find("al") # """ 寻找子序列位置,如果没找到,返回 -1 """def find(self, sub, start=None, end=None):可以定义开始和结束的位置,S.find(sub [,start [,end]]) -> int
print(s.find("al"))
s1 = "hello {0},age {1}" # {0},{1}可以充当占位符
a4 = s1.format("alex",18) # """ 字符串格式化,动态参数,将函数式编程时细说 """def format(*args, **kwargs):S.format(*args, **kwargs) -> string
print(s1, a4)
print(s.index("ll")) # """ 子序列位置,如果没找到,报错 """ def index(self, sub, start=None, end=None):可以定义开始和结束的位置,S.index(sub [,start [,end]]) -> int
num1 = "dasfsdfaa"
num2 = "jkljljl"
num3 = ""
num4 = "kkk* &687689"
num5 = " "
num6 = "Alss Sss 888&&&L "
num7 = "ALJL"
print(num1.isalnum()) # """ 是否是字母或数字组成"""必须要字母和数字组成的字符串,含有其他字符返回FalseS.isalnum() -> bool
print(num2.isalpha())
# """ 是否全是字母 """
print(num3.isdigit()) # """ 是否全是数字 """
print(num4.islower()) # """ 这里面的字母是否小写 """可以包含其他字符
print(num5.isspace())
# 是否全是空格,且自少有一个字符
print(num6.istitle()) # 是否是标题,所有首字母都是大写
print(num7.title())
# 变成标题
print(num7.isupper())
# 是否全是大写
li = ["alex", "eric"]
li2 = ("alex", "eric")
print("_".join(li2))
# """ 连接 """def join(self, iterable): 参数是可迭代的,循环li的元素,让每个元素用“_”连接起来 pp = "alexKKK000***1111"
print(pp.ljust(20, "*"))
# """ 内容左对齐,右侧填充 """width:总长度;fillchar:空白处填充内容,默认无。-> string
print(pp.rjust(20, "*"))
# 内容右对齐
print(pp.lower())
# 字母全部变成小写-> string
print(pp.upper())
# 字母全部变成大写-> string
print(pp.swapcase())
# 小写变大写,大写变小写
kb = " kkkkfasdfa jkljlk "
print(kb.lstrip())
# """ 移除左侧空白 """
print(kb.rstrip())
# """ 移除右侧空白 """
print(kb.strip())
# """ 移除两侧的空白 """ sb = "alex SB alex SB"
print(sb.partition("SB"))
# """ 分割,前,中,后三部分 """添加到一个元祖里面S.partition(sep) -> (head, sep, tail)
print(sb.replace("SB", "HH"))
# """ 替换 """count参数是替换几个的意思
print(sb.replace("SB", "HH", 1)) fg = "alexalex"
print(fg.split("e"))
# """ 分割, maxsplit最多分割几次 """S.split([sep [,maxsplit]]) -> list of strings
print(fg.split("e", 1))
fg1 = "alex\nalex"
print(fg.splitlines()) # """ 根据换行分割 """
“jljl$ fsaldkfj6sdfjlasjdl”.title 数字特殊字符空格割开的第一个字母大写。
print("abalex".strip("a")) out:balex 。
print("aba*lex*".strip("a*")) out:ba*lex。
4、列表
创建列表:
name_list = ['alex', 'seven', 'eric']
或
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_listreturn
-
class list(object):
"""
list() -> new empty list
list(iterable) -> new list initialized from iterable's items
"""
def append(self, p_object): # real signature unknown; restored from __doc__
""" 添加 元素
L.append(object) -> None -- append object to end """
pass def clear(self): # real signature unknown; restored from __doc__
""" 清空元素
L.clear() -> None -- remove all items from L """
pass def copy(self): # real signature unknown; restored from __doc__
""" 浅copy L.copy() -> list -- a shallow copy of L """
return [] def count(self, value): # real signature unknown; restored from __doc__
""" 匹配 value的个数 L.count(value) -> integer -- return number of occurrences of value """
return 0 def extend(self, iterable): # real signature unknown; restored from __doc__
""" 拼接两个列表 L.extend(iterable) -> None -- extend list by appending elements from the iterable """
pass def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
""" 返回 某个value 的索引
L.index(value, [start, [stop]]) -> integer -- return first index of value.
Raises ValueError if the value is not present.
"""
return 0 def insert(self, index, p_object): # real signature unknown; restored from __doc__
""" 指定索引位置处添加元素 L.insert(index, object) -- insert object before index """
pass def pop(self, index=None): # real signature unknown; restored from __doc__
""" 删除结尾的元素
L.pop([index]) -> item -- remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.
"""
pass def remove(self, value): # real signature unknown; restored from __doc__
""" 移除 从左测匹配的第一个元素
L.remove(value) -> None -- remove first occurrence of value.
Raises ValueError if the value is not present.
"""
pass def reverse(self): # real signature unknown; restored from __doc__
""" 反转列表 L.reverse() -- reverse *IN PLACE* """
pass def sort(self, key=None, reverse=False): # real signature unknown; restored from __doc__
""" 排序 但是int str不行 L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """
pass def __add__(self, *args, **kwargs): # real signature unknown
""" Return self+value. """
pass def __contains__(self, *args, **kwargs): # real signature unknown
""" Return key in self. """
pass def __delitem__(self, *args, **kwargs): # real signature unknown
""" Delete self[key]. """
pass def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass def __getitem__(self, y): # real signature unknown; restored from __doc__
""" x.__getitem__(y) <==> x[y] """
pass def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass def __iadd__(self, *args, **kwargs): # real signature unknown
""" Implement self+=value. """
pass def __imul__(self, *args, **kwargs): # real signature unknown
""" Implement self*=value. """
pass def __init__(self, seq=()): # known special case of list.__init__
"""
list() -> new empty list
list(iterable) -> new list initialized from iterable's items
# (copied from class doc)
"""
pass def __iter__(self, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass def __len__(self, *args, **kwargs): # real signature unknown
""" Return len(self). """
pass def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass def __mul__(self, *args, **kwargs): # real signature unknown
""" Return self*value.n """
pass @staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass def __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass def __reversed__(self): # real signature unknown; restored from __doc__
""" L.__reversed__() -- return a reverse iterator over the list """
pass def __rmul__(self, *args, **kwargs): # real signature unknown
""" Return self*value. """
pass def __setitem__(self, *args, **kwargs): # real signature unknown
""" Set self[key] to value. """
pass def __sizeof__(self): # real signature unknown; restored from __doc__
""" L.__sizeof__() -- size of L in memory, in bytes """
pass __hash__ = None
示例:
###### 列表 ########## #!/usr/bin/env python
# _*_ coding:utf-8 _*_ lis=[1,2,3,'alex']
cc=[5,5]
print(lis.count("alex"))
lis.extend(cc)
print(lis) name_list = ["eirc", "alex", 'tony']
"""
# 索引
print(name_list[0])
# 切片
print(name_list[0:2])
# len
print(name_list[2:len(name_list)])
# for
for i in name_list:
print(i) #join 方法,拼接字符串
li = ["alex","eric"]
name = "li jie"
ss = "_".join(li)
s = "_".join(name)
print(s,ss) """
# 列表内部提供的其他功能
# append后追加
name_list.append('seven')
name_list.append('seven')
name_list.append('seven')
print(name_list)
# 元素出现的次数
print(name_list.count('seven'))
# iterable,可迭代的
temp = [111,22,33,44]
# 扩展,批量添加
name_list.extend(temp)
print(name_list)
# 获取指定元素的索引位置
print(name_list.index('alex'))
# 向指定索引位置插入数据
name_list.insert(1, 'SB')
print(name_list)
# 在原列表中移除掉最后一个元素,并将其赋值给 a1
a1 = name_list.pop()
print(name_list)
print(a1)
# 移除某个元素
name_list.remove('seven')
print(name_list)
# 翻转
name_list.reverse()
print(name_list) # 删除指定索引位置
print(name_list)
del name_list[1:3]
print(name_list)
列表练习:
# list列表方法练习
name_list = ['alex', 'seven', 'eric'] #增加
name_list.append("seven") # 在末尾追加
name_list.append("seven")
print(name_list) temp = [11, "bb", 222]
name_list.extend(temp) # 本身后面添加可迭代的参数,
print(name_list)
name_list.extend("abc") # 本身后面添加可迭代的参数
print(name_list) name_list.insert(1, "sb") # 在某个位置插入
print(name_list) #查找
print(name_list.count("seven")) # 统计出现的次数
# iterable可迭代的,只要能够通过for循环的 都是可迭代的。 print(name_list.index(11)) # 索引,查位置,参数:str,start,end。可以添加索引范围的。 #删除
del name_list[1] #直接del删除,索引擅长,超出报错
print(name_list)
a = name_list.pop() # 默认尾部删掉,可赋值给别人,如果删完了会报错
print(name_list, a)
a = name_list.pop(2) #索引删除并赋值,如果超出索引报错
print(name_list, a)
x = name_list.remove("seven") # 只移除找到的第一个,不可赋值,找不到时报错
print(name_list, x) #x是None,无法赋值
# name_list.clear() #直接清空 name_list4 = ["eirc", "andy", "ALex"]
del name_list4[1]
# 删除列表指定位置的元素,索引位置,可用切片
print(name_list4) # 反转
name_list.reverse() #列表翻转
print(name_list) # 排序,里面的元素类型必须一致
name_list2 = [1, 2, 44, 52, 4, 2, 55, 2]
name_list3 = ["kksaj", "jalkdjl", "ax", "bb"]
name_list3.sort() print(name_list3)
#join 方法,拼接字符串
#join 方法,拼接字符串
li = ["alex","eric"]
name = "li jie"
ss = "_".join(li)
s = "_".join(name)
print(s,ss)
join是从可迭代的元素第一个元素后面开始拼接,在其他元素前面加上“ ”中的元素进行拼接
print("_".join(["abc","ef"]))
print("_".join("alex li")) abc_ef
a_l_e_x_ _l_i
5、元祖
创建元祖: 元组一旦创建 不等增加也不能减少
- 索引
- 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
class tuple(object):
"""
tuple() -> empty tuple
tuple(iterable) -> tuple initialized from iterable's items If the argument is a tuple, the return value is the same object.
"""
def count(self, value): # real signature unknown; restored from __doc__
""" 计算 value的个数 T.count(value) -> integer -- return number of occurrences of value """
return 0 def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
""" 索引
T.index(value, [start, [stop]]) -> integer -- return first index of value.
Raises ValueError if the value is not present.
"""
return 0 def __add__(self, *args, **kwargs): # real signature unknown
""" Return self+value. """
pass def __contains__(self, *args, **kwargs): # real signature unknown
""" Return key in self. """
pass def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass def __getitem__(self, *args, **kwargs): # real signature unknown
""" Return self[key]. """
pass def __getnewargs__(self, *args, **kwargs): # real signature unknown
pass def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass def __hash__(self, *args, **kwargs): # real signature unknown
""" Return hash(self). """
pass def __init__(self, seq=()): # known special case of tuple.__init__
"""
tuple() -> empty tuple
tuple(iterable) -> tuple initialized from iterable's items If the argument is a tuple, the return value is the same object.
# (copied from class doc)
"""
pass def __iter__(self, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass def __len__(self, *args, **kwargs): # real signature unknown
""" Return len(self). """
pass def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass def __mul__(self, *args, **kwargs): # real signature unknown
""" Return self*value.n """
pass @staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass def __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass def __rmul__(self, *args, **kwargs): # real signature unknown
""" Return self*value. """
pass
示例:
############### 元组 #################
name_tuple = ('alex', 'eric')
# 索引
print(name_tuple[0])
# len
print(name_tuple[len(name_tuple)-1])
# 切片
print(name_tuple[0:1])
# for
for i in name_tuple:
print(i)
# 删除
# del name_tuple[0] 不支持
# count,计算元素出现的个数
print(name_tuple.count('alex'))
# index 获取指定元素的索引位置
print(name_tuple.index('alex'))
示例练习:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# tuple元祖的特殊方法练习
name_list = ('alex', 'seven', 'eric', "alex")
print(name_list.index("alex")) # 获取指定元素的索引编号
print(name_list.count("alex")) # 获取指定元素的个数 # tuple(列表)列表变元组
a = range(10)
print(a) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
d = tuple(a)
print(d) # (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
# list(元组)元组变列表
print(d) # (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
e = list(a)
print(e) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] #有些时候我们的列表数据不想被人修改时怎么办? 就可以用元组存放,元组又被称为只读列表,不能修改。
# 定义:与列表类似,只不过[]改成(),很多用法和list一致, # 注意:元组本身不可变,如果元组中还包含其他可变元素,这些可变元素可以改变 data = (99, 88, 77, ['Alex', 'Jack'], 33)
data[3][0] = '金角大王'
print(data) # (99, 88, 77, ['金角大王', 'Jack'], 33)
# 为啥呢? 因为元组只是存每个元素的内存地址,上面[‘金角大王’, ‘Jack’]这个列表本身的内存地址存在元组里确实不可变,但是这个列表包含的元素的内存地址是存在另外一块空间里的,是可变的。
6、字典(无序)
创建字典:
user_info={"name":"alex",
"age":18,
"gender":"M",
}
li=["kk","jkjkj","sdfj"]
new_dict=dict(enumerate(li))
print new_dict #{0: 'kk', 1: 'jkjkj', 2: 'sdfj'}
创建操作 >>>person = {"name": "alex", 'age': 20}
#或
>>>person = dict(name='seven', age=20)
#或
>>>person = dict({"name": "egon", 'age': 20})
#或
>>> {}.fromkeys([1,2,3,4,5,6,7,8],100)
{1: 100, 2: 100, 3: 100, 4: 100, 5: 100, 6: 100, 7: 100, 8: 100}
增加操作 names = {
"alex": [23, "CEO", 66000],
"黑姑娘": [24, "行政", 4000],
}
# 新增k
names["佩奇"] = [26, "讲师", 40000]
names.setdefault("oldboy",[50,"boss",100000]) # D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
删除操作 names.pop("alex") # 删除指定key
names.popitem() # 随便删除1个key
del names["oldboy"] # 删除指定key,同pop方法
names.clear() # 清空dict
修改操作 dic['key'] = 'new_value',如果key在字典中存在,'new_value'将会替代原来的value值;
dic.update(dic2) 将字典dic2的键值对添加到字典dic中,如果有重复的key,这更新value值
查操作 dic['key'] #返回字典中key对应的值,若key不存在字典中,则报错;
dic.get(key, default = None)#返回字典中key对应的值,若key不存在字典中,则返回default的值(default默认为None)
'key' in dic #若存在则返回True,没有则返回False
dic.keys() 返回一个包含字典所有KEY的列表;
dic.values() 返回一个包含字典所有value的列表;
dic.items() 返回一个包含所有(键,值)元组的列表;
循环 1、for k in dic.keys()
2、for k,v in dic.items()
3、for k in dic # 推荐用这种,效率速度最快
info = {
"name":"小猿圈",
"mission": "帮一千万极客高效学编程",
"website": "http://apeland.com"
}
for k in info:
print(k,info[k])
输出
name 小猿圈
mission 帮一千万极客高效学编程
website http://apeland.com
求长度 len(dic)
常用操作:
- 索引
-
print user_info["name"]print user_info["age"]
-
- 新增
- 直接添加user_info["新的键"]="新的值"
- user_info.update({"kkk":"xxx"})
- 删除
- pop
- 键、值、键值对
- 循环
for item in user_info: #默认输出的是keys
print item
for item in user_info.values: #获取所有的值
print item
for i j in user_info.items: #获取所有的键值对
print i,j
user_info.keys() #获取所有的key
user_info.values() #获取所有的值
user_info.items() #获取所有的键值对
- 长度
- len(user_info)
class dict(object):
"""
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
dict(iterable) -> new dictionary initialized as if via:
d = {}
for k, v in iterable:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
"""
def clear(self): # real signature unknown; restored from __doc__
""" 清除 字典 D.clear() -> None. Remove all items from D. """
pass def copy(self): # real signature unknown; restored from __doc__
""" 浅拷贝 D.copy() -> a shallow copy of D """
pass @staticmethod # known case
def fromkeys(*args, **kwargs): # real signature unknown
""" Returns a new dict with keys from iterable and values equal to value. """
pass def get(self, k, d=None): # real signature unknown; restored from __doc__
""" 根据key获取 d是默认是 为 None D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """
pass def items(self): # real signature unknown; restored from __doc__
""" 将字典的key value都打印成列表元组 D.items() -> a set-like object providing a view on D's items """
pass def keys(self): # real signature unknown; restored from __doc__
"""打印字典的key D.keys() -> a set-like object providing a view on D's keys """
pass def pop(self, k, d=None): # real signature unknown; restored from __doc__
""" 获取并在字典中移除
D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised
"""
pass def popitem(self): # real signature unknown; restored from __doc__
""" 获取并在列表中移除
D.popitem() -> (k, v), remove and return some (key, value) pair as a
2-tuple; but raise KeyError if D is empty.
"""
pass def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
"""如果key不存在,则创建,如果存在,则返回已存在的值且不修改 D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
pass def update(self, E=None, **F): # known special case of dict.update
"""
D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
In either case, this is followed by: for k in F: D[k] = F[k]
"""
pass def values(self): # real signature unknown; restored from __doc__
""" 所有的值 D.values() -> an object providing a view on D's values """
pass def __contains__(self, *args, **kwargs): # real signature unknown
""" True if D has a key k, else False. """
pass def __delitem__(self, *args, **kwargs): # real signature unknown
""" Delete self[key]. """
pass def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass def __getitem__(self, y): # real signature unknown; restored from __doc__
""" x.__getitem__(y) <==> x[y] """
pass def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass def __init__(self, seq=None, **kwargs): # known special case of dict.__init__
"""
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
dict(iterable) -> new dictionary initialized as if via:
d = {}
for k, v in iterable:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
# (copied from class doc)
"""
pass def __iter__(self, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass def __len__(self, *args, **kwargs): # real signature unknown
""" Return len(self). """
pass def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass @staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass def __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass def __setitem__(self, *args, **kwargs): # real signature unknown
""" Set self[key] to value. """
pass def __sizeof__(self): # real signature unknown; restored from __doc__
""" D.__sizeof__() -> size of D in memory, in bytes """
pass __hash__ = None
示例:
#!/usr/bin/env python
# _*_ coding:utf-8 _*_ dic={1:2,"alex":4,4:9}
print(dic.get("alex"))
print(dic.items())
print(dic.keys())
print(dic.values())
print(dic.pop(2,None))
print(dic.setdefault("name","rain")) ###################### 字典 ###################
# 字典的每一个元素,键值对
user_info = {
0: "alex",
"age": 73,
2: 'M'
}
# 0 “alex"
# 1 73 # 索引
# print(user_info[0])
# print(user_info["age"]) # 循环,默认值输出key
# for i in user_info:
# print(i) # # 获取所有键
# print(user_info.keys())
# # 获取所有值
# print(user_info.values())
# # 获取所有键值对
# print(user_info.items()) # for i in user_info.keys():
# print(i)
#
# for i in user_info.values():
# print(i) # user_info = {
# 0: "alex",
# "age": 73,
# 2: 'M'
# }
# for k,v in user_info.items():
# print(k)
# print(v) # clear,清除所有内容
# user_info.clear()
# print(user_info) # get 根据key获取值,如果key不存在,可以指定一个默认值
# val = user_info.get('age')
# print(val)
# val = user_info.get('age', '123')
# print(val)
# 索引取值时,key不存在,报错
# print(user_info['age'])
# print(user_info['age1111']) # has_key 检查字典中指定key是否存在 3版本python没有了 可以用in 判断
# ret = 'agfffe' in user_info.keys()
# print(ret)
# pop # popitem # update
# print(user_info)
# test = {
# "a1": 123,
# 'a2': 456
# }
# user_info.update(test)
# print(user_info) # 删除指定索引的键值对
test = {
"a1": 123,
'a2': 456
} del test['a1']
print(test)
示例练习:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#dict字典的特殊方法 user_info={"name":"alex",
"age":18,
"gender":"M"
}
print len(user_info)#长度
#user_info.clear()#清空字典,清楚所有内容
print user_info.get("name")
print user_info.get("name1",123) # """ 根据key获取值,d是默认值 """如果key不存在,返回默认值,不会报错
print user_info["name"] #如果不存在会报错
print user_info.has_key("name") #""" 是否有key """
a=user_info.pop("age")#获取并在字典中移除,可以将key赋值给一个变量
print user_info,a
a=user_info.popitem()#移除key values 赋值给一个元祖中
print user_info, user_info.iteritems()
print user_info
user_info.update({"kkk":"jjk"})#更新
print user_info #@staticmethod,类方法
user_info_new=dict.fromkeys(["k","name"],"alex")
print user_info_new
2版本python 查看字典有没有这个key
>>> contact['']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: ''
>>> contact.has_key('')
False
>>> contact.has_key('')
True
清空字典contact.clear()
>>> contact.clear()
5、for循环
li = [11,22,33]
for i in li:
print(li.index(i),i)
6、enumrate
为可迭代的对象添加序号
li = [11,22,33]
for k,v in enumerate(li, 1):
print(k,v)
7、range 和xrange
print range(1, 10)
# 结果:[1, 2, 3, 4, 5, 6, 7, 8, 9] print range(1, 10, 2)
# 结果:[1, 3, 5, 7, 9] print range(30, 0, -2)
# 结果:[30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2] 例如 :
print(range(1,10))
没有循环,因此输出 range(1, 10) 而不是1 2 3.。。10
8、练习题
1、元素分类
有如下值集合 [11,22,33,44,55,66,77,88,99,90],将所有大于 66 的值保存至字典的第一个key中,将小于等于 66 的值保存至第二个key的值中。
即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}
#!/usr/bin/env python
# -*- coding:utf-8 -*-
lis=[11,22,33,44,55,66,77,88,99,90]
dic={"k1":[],"k2":[]}
for i in lis:
if i>66:
dic["k1"].append(i)
else:
dic["k2"].append(i)
print dic
#!/usr/bin/env python
# -*- coding:utf-8 -*-
li = ["alec", " Aric", "Alei", "Tony", "rain"]
tu = ("alec", " Aric", "Alei", "Tony", "rain")
dic = {'k1': "alei", 'k2': ' aric', "k3": "Alec", "k4": "Tony"}
li_new = []
tu_new = []
dic_new={}
for i in li:
i=i.strip()
#if判断顺序,从前往后,or,自己成功就行了,and。
if (i.startswith("a") or i.startswith("A")) and i.endswith("c"):
li_new.append(i)
else:
pass
for i in tu:
i=i.strip()
if (i.startswith("a") or i.startswith("A")) and i.endswith("c"):
tu_new.append(i)
else:
pass
for i,j in dic.items():
j=j.strip()
if (j.startswith("a") or j.startswith("A")) and j.endswith("c"):
# dic_new.update({i:j})
dic_new[i]=j
else:
pass
print li_new
print tu_new
print dic_new
#!/usr/bin/env python
# -*- coding:utf-8 -*-
li=["手机", "电脑", '鼠标垫', '游艇']
for i,j in enumerate(li,1):
print i,j
inp=int(raw_input("请选择:"))
print li[inp-1]
功能要求:
- 要求用户输入总资产,例如:2000
- 显示商品列表,让用户根据序号选择商品,加入购物车
- 购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。
- 附加:可充值、某商品移除购物车
#!/usr/bin/env python
# -*- coding:utf-8 -*-
goods = [
{"name": "电脑", "price": 1999},
{"name": "鼠标", "price": 10},
{"name": "游艇", "price": 20},
{"name": "美女", "price": 998},
]
glod=int(input("您的总资产为:"))
def show_goods():
for i in goods:
print(str(goods.index(i)) + ":" + i["name"], i["price"], "元")
print("4:结算")
def show_gwc():
for item in gwc.items():
print(item[0], "数量:" + str(item[1]["数量"]), "单价:" + str(item[1]["单价"]))
total=0
gwc={}
show_goods()
while True:
get_goods=int(input("请输入你要购买的商品编号,结算请输入4:"))
if get_goods<3:
if goods[get_goods]["name"] in gwc.keys():
gwc[goods[get_goods]["name"]]["数量"]+=1
else:
gwc[goods[get_goods]["name"]] = {"数量": 1, "单价": goods[get_goods]["price"]}
total = total + goods[get_goods]["price"]
show_gwc()
show_goods()
continue
elif get_goods>4:
print("输入错误")
show_goods()
continue
else:
if total<=glod:
print("你购买的商品总额为%d元,购买成功" % total)
else:
print("余额不足")
break