Python 基础部分-2

Pycharm

PyCharm是一种Python IDE,带有一整套可以帮助用户在使用Python语言开发时提高其效率的工具,比如调试、语法高亮、Project管理、代码跳转、智能提示、自动完成、单元测试、版本控制。此外,该IDE提供了一些高级功能,以用于支持Django框架下的专业Web开发。

解释器设定

file > setting > Editor > file and code template > python script > 右上方

#!/usr/bin/env python

# -*- coding:utf-8 -*- (适用python2.7)

from __future__ import division 

文字设定

file > setting > Editor > color and font > font > save as > 选择“size”

 

更换编译器版本

file > setting > project interpreter > 选择已安装的版本

运行程序

Ctrl + Shift + F10, 或点击鼠标右键选择'run'

算数运算:

计算中整数与浮点数的转换

#Python2.7:

    9/2 = 4

    9/2 = 4.5(导入模块)

#Python3.x:

    9/2 = 4.5

增量赋值

x = x + 1
x += 1

#同理可得
+=    -=    *=    /=    %=   **=

比较运算:

赋值运算:

逻辑运算:

成员运算:

s= "Alex"
ret = "Ax" in s 
print(ret)
>>> False

li = ["Alex", "Eric", "Rain"]
ret = "Alex" in li
print(ret)
>>>True

#列表最小单位为“  ”的内容
li = ["Alex", "Eric", "Rain"]
ret = "Ax" in li
print(ret)
>>>False

Python运算的优先级

a = 50
b = 100
c = 10
d = 5
e = 0

e = (a + b) * c / d       #( 150 * 10 ) / 5
>>>300

e = a + (b * c) / d;      #  50 + (1000/5)
>>>250

基本数据类型

 

整数 int
字符串 str
布尔类型 bool
列表 list
元组 tuple
字典 dict

基本数据类型(对象)所具备的功能都保存在相应的 类 

查看对象的类,或对象所具备的功能

type()

temp = "Alex"
t=type(temp)
print(t)

#str, ctrl + 鼠标左键, 找到 str类, 内部所有的方法

dir()

temp = 'alex'
b = dir(temp)
print(b)

#输出str相关的函数

help(type())

 #查找相应帮助文档

解释器Pycharm直接点击查找帮助

temp = "Alex"
temp.upper()

鼠标放在upper()上, ctrl + 左键, 自动定位到upper功能处

基本数据类型的常用功能

1. 整数

创建方式

n =123            根据int类,创建了一个对象

n = int(123)     根据int类,创建了一个对象(运行了int类里面的内部函数)

def __int__(self): # real signature unknown; restored from __doc__
        """ x.__int__() <==> int(x) """
#创建方式
a1=int(123) print(a1) >>>123 a2 = int("0b100", 2)#以二进制输入装换为十进制 print(a2) >>>4
def __init__(self, x, base=10): # known special case of int.__init__
    """
    int(x=0) -> int or long
    int(x, base=10) -> int or long

运算 

n1= 123
n2= 456
print(n1+n2)#= print(n1.__add__(n2))
def __add__(self, y): # real signature unknown; restored from __doc__
        """ x.__add__(y) <==> x+y """ 

长度限制(python2.7)

#int长度限制,python2.7中超出范围转换为Long类型(没有长度限制)
    int范围:
        32位系统  -2**31 ~ 2**31
        64位系统  -2**63 ~ 2**63
1 >>>n1 = 2**31#32位系统中
2 >>>n1 = 2147483648L
3 >>>m1 = n1 - 1
4 >>>m1
5 >>>2147483647

整数变量的内存指向方式

a.                                                                     b.

n1 = 123                       n1 = 123

n2 = 123                     n2 = n1

Python整数变量的内存优化

#变量在-5~257内,Python优化只开辟一个内存地址,使多个变量指向同一个内存地址
>>> n1 = 123
>>> n2 = 123

>>> id(n1)
491937424
>>> id(n2)
491937424

#变量在-5~257外,分别开辟两不用内存地址
>>> n1 = 123456
>>> n2 = 123456

>>> id(n1)
48915008
>>> id(n2)
48915680

整数的二进制位数

获取可表示的二进制最短位数

n1 =  4 #000000100
ret = n1.bit_length()
print(ret)
>>>3
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
int
2. 布尔值
  
  真或假, True or False
  False: None/False/空字符串""/0/空列表[]/空字典{}/空元组() 
      True: 其它的都相当于

3. 字符串

字符串的创建

#创建字符串
s1 = "sam"
s1 = str('sam')
s1 = '  '  #无参数
#无参数,创建空字符串 #一个参数,创建普通字符串 #两个参数,str(字节,编码)
str(字节类型, 编码)
    def __init__(self, value='', encoding=None, errors='strict'): # known special case of str.__init__
        """
        str(object='') -> str
        str(bytes_or_buffer[, encoding[, errors]]) -> str
字符串常用功能:
  • 移除空白
  • 分割
  • 长度
  • 索引
  • 切片
#capitalize()
a1= "alex" ret = a1. capitalize() print(ret) >>>Alex
#center() a1
= "alex" ret = a1.center(20, '***') print(ret) >>>**********alex**********
#count() a1
= "alex is alph" ret = a1.count("al", 0, 4) #count("srt", start, end) print(ret) >>>1
#endswith() temp
= "hello" print(temp.endswith('e', 0, 2)) #endswith('str', start, end) >>>False
#expandtabs()
content = "hello 999" print(content) print(content.expandtabs()) print(content.expandtabs(20)) >>>hello 999 >>>hello 999 >>>hello 999
#find() s
= "alex hello" print s.find("ex")#查找字符匹配的位置 print s.find("i") >>>2 >>>-1
#format()
s = "hello {0}, age{1}"#{0},{1}占位符 new1 = s.format('alex', 19) #s.format('A','B')把format内容按占位符顺序加入到原来的变量里 print(new1) >>> hello alex, age 19
#join()
li = ["alex", "eric"]
s = "_".join(li)
print(s)

>>>'alex_eric'
#strip, rstrip, lstrip
s=" al ex " news1 = s.lstrip()#移除后需建立新的列表接收 news2 = s.rstrip() new = s.strip() print(new) >>>"al ex " >>>" al ex" >>>"al ex"
#partation
s = "alex is man" ret = s.partition("is") print(ret) >>>('alex ', 'is', ' man')#生成元组类型 #replace() s = "alex is man" ret = s.replace("man", "guy") print(ret) >>>alex is guy
#split()
s="alexalex" ret = s.split("e", 1)#从左边第一个"e"中分开字符串 print(ret) >>>['al', 'xalex']
#swapcase()
s="aLeX" print(s.swapcase()) >>>"AlEx"
#title() s
= "the school" ret = s.title() print(ret) >>>The School
#upper, lower

s1 = "sam"
s1.upper()
>>>'SAM'

s1.lower()
>>>'sam'
#isdigit() 

a = '123'#字符串
b = '12$'#字符串

print (a.isdigit())
>>>
True

print (b.isdigit())
>>>
False
#translate 
from string import maketrans

intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)

str = "this is string example....wow!!!"
print (str.translate(trantab))

>>>
th3s 3s str3ng 2x1mpl2....w4w!!!

索引

  只能取一个元素

s = "alex"

#索引
print(s[0])
print(s[1])
print(s[2])
print(s[3])
ret = len(s)#字符长度
print (len)

切片

  获取取多个元素

s= "alex" 

print(s[0:2])
#0=<  0, 1 < 2
>>>al
s = 'hello world!'
sliceS1 = s[::1]
sliceS2 = s[::-1]
print (sliceS1,sliceS2)

>>>
hello world! !dlrow olleh

for 循环 在str的应用

    def __iter__(self, *args, **kwargs): # str内置函数中,存在迭代功能
        """ Implement iter(self). """
s = "alex"

start = 0
while start < len(s):
        temp = s[start]
        print(temp)
        start += 1
>>>a
>>>l
>>>e
>>>x
s = "alex"
#for循环,break,continue
for item in s:
        if item == 'l':
              break  
        print(item)
>>>a
class str(basestring):
    """
    str(object='') -> string
    
    Return a nice string representation of the object.
    If the argument is a string, the return value is the same object.
    """
    def capitalize(self):  
        """ 首字母变大写 """
        """
        S.capitalize() -> string
        
        Return a copy of the string S with only its first character
        capitalized.
        """
        return ""

    def center(self, width, fillchar=None):  
        """ 内容居中,width:总长度;fillchar:空白处填充内容,默认无 """
        """
        S.center(width[, fillchar]) -> string
        
        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):  
        """ 子序列个数 """
        """
        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 decode(self, encoding=None, errors=None):  
        """ 解码 """
        """
        S.decode([encoding[,errors]]) -> object
        
        Decodes S using the codec registered for encoding. encoding defaults
        to the default encoding. errors may be given to set a different error
        handling scheme. Default is 'strict' meaning that encoding errors raise
        a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
        as well as any other name registered with codecs.register_error that is
        able to handle UnicodeDecodeErrors.
        """
        return object()

    def encode(self, encoding=None, errors=None):  
        """ 编码,针对unicode """
        """
        S.encode([encoding[,errors]]) -> object
        
        Encodes S using the codec registered for encoding. encoding defaults
        to the default encoding. 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 is able to handle UnicodeEncodeErrors.
        """
        return object()

    def endswith(self, suffix, start=None, end=None):  
        """ 是否以 xxx 结束 """
        """
        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=None):  
        """ 将tab转换成空格,默认一个tab转换成8个空格 """
        """
        S.expandtabs([tabsize]) -> string
        
        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):  
        """ 寻找子序列位置,如果没找到,返回 -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.format(*args, **kwargs) -> string
        
        Return a formatted version of S, using substitutions from args and kwargs.
        The substitutions are identified by braces ('{' and '}').
        """
        pass

    def index(self, sub, start=None, end=None):  
        """ 子序列位置,如果没找到,报错 """
        S.index(sub [,start [,end]]) -> int
        
        Like S.find() but raise ValueError when the substring is not found.
        """
        return 0

    def isalnum(self):  
        """ 是否是字母和数字 """
        """
        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):  
        """ 是否是字母 """
        """
        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 isdigit(self):  
        """ 是否是数字 """
        """
        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 islower(self):  
        """ 是否小写 """
        """
        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 isspace(self):  
        """
        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):  
        """
        S.istitle() -> bool
        
        Return True if S is a titlecased string and there is at least one
        character in S, i.e. uppercase characters may only follow uncased
        characters and lowercase characters only cased ones. Return False
        otherwise.
        """
        return False

    def isupper(self):  
        """
        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):  
        """ 连接 """
        """
        S.join(iterable) -> string
        
        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):  
        """ 内容左对齐,右侧填充 """
        """
        S.ljust(width[, fillchar]) -> string
        
        Return S left-justified in a string of length width. Padding is
        done using the specified fill character (default is a space).
        """
        return ""

    def lower(self):  
        """ 变小写 """
        """
        S.lower() -> string
        
        Return a copy of the string S converted to lowercase.
        """
        return ""

    def lstrip(self, chars=None):  
        """ 移除左侧空白 """
        """
        S.lstrip([chars]) -> string or unicode
        
        Return a copy of the string S with leading whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        If chars is unicode, S will be converted to unicode before stripping
        """
        return ""

    def partition(self, sep):  
        """ 分割,前,中,后三部分 """
        """
        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):  
        """ 替换 """
        """
        S.replace(old, new[, count]) -> string
        
        Return a copy of string 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):  
        """
        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):  
        """
        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):  
        """
        S.rjust(width[, fillchar]) -> string
        
        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):  
        """
        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=None):  
        """
        S.rsplit([sep [,maxsplit]]) -> list of strings
        
        Return a list of the words in the string 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 or is None, any whitespace string
        is a separator.
        """
        return []

    def rstrip(self, chars=None):  
        """
        S.rstrip([chars]) -> string or unicode
        
        Return a copy of the string S with trailing whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        If chars is unicode, S will be converted to unicode before stripping
        """
        return ""

    def split(self, sep=None, maxsplit=None):  
        """ 分割, maxsplit最多分割几次 """
        """
        S.split([sep [,maxsplit]]) -> list of strings
        
        Return a list of the words in the string 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=False):  
        """ 根据换行分割 """
        """
        S.splitlines(keepends=False) -> 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):  
        """ 是否起始 """
        """
        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):  
        """ 移除两段空白 """
        """
        S.strip([chars]) -> string or unicode
        
        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.
        If chars is unicode, S will be converted to unicode before stripping
        """
        return ""

    def swapcase(self):  
        """ 大写变小写,小写变大写 """
        """
        S.swapcase() -> string
        
        Return a copy of the string S with uppercase characters
        converted to lowercase and vice versa.
        """
        return ""

    def title(self):  
        """
        S.title() -> string
        
        Return a titlecased version of S, i.e. words start with uppercase
        characters, all remaining cased characters have lowercase.
        """
        return ""

    def translate(self, table, deletechars=None):  
        """
        转换,需要先做一个对应表,最后一个表示删除字符集合
        intab = "aeiou"
        outtab = "12345"
        trantab = maketrans(intab, outtab)
        str = "this is string example....wow!!!"
        print str.translate(trantab, 'xm')
        """

        """
        S.translate(table [,deletechars]) -> string
        
        Return a copy of the string S, where all characters occurring
        in the optional argument deletechars are removed, and the
        remaining characters have been mapped through the given
        translation table, which must be a string of length 256 or None.
        If the table argument is None, no translation is applied and
        the operation simply removes the characters in deletechars.
        """
        return ""

    def upper(self):  
        """
        S.upper() -> string
        
        Return a copy of the string S converted to uppercase.
        """
        return ""

    def zfill(self, width):  
        """方法返回指定长度的字符串,原字符串右对齐,前面填充0。"""
        """
        S.zfill(width) -> string
        
        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 _formatter_field_name_split(self, *args, **kwargs): # real signature unknown
        pass

    def _formatter_parser(self, *args, **kwargs): # real signature unknown
        pass

    def __add__(self, y):  
        """ x.__add__(y) <==> x+y """
        pass

    def __contains__(self, y):  
        """ x.__contains__(y) <==> y in x """
        pass

    def __eq__(self, y):  
        """ x.__eq__(y) <==> x==y """
        pass

    def __format__(self, format_spec):  
        """
        S.__format__(format_spec) -> string
        
        Return a formatted version of S as described by format_spec.
        """
        return ""

    def __getattribute__(self, name):  
        """ x.__getattribute__('name') <==> x.name """
        pass

    def __getitem__(self, y):  
        """ x.__getitem__(y) <==> x[y] """
        pass

    def __getnewargs__(self, *args, **kwargs): # real signature unknown
        pass

    def __getslice__(self, i, j):  
        """
        x.__getslice__(i, j) <==> x[i:j]
                   
                   Use of negative indices is not supported.
        """
        pass

    def __ge__(self, y):  
        """ x.__ge__(y) <==> x>=y """
        pass

    def __gt__(self, y):  
        """ x.__gt__(y) <==> x>y """
        pass

    def __hash__(self):  
        """ x.__hash__() <==> hash(x) """
        pass

    def __init__(self, string=''): # known special case of str.__init__
        """
        str(object='') -> string
        
        Return a nice string representation of the object.
        If the argument is a string, the return value is the same object.
        # (copied from class doc)
        """
        pass

    def __len__(self):  
        """ x.__len__() <==> len(x) """
        pass

    def __le__(self, y):  
        """ x.__le__(y) <==> x<=y """
        pass

    def __lt__(self, y):  
        """ x.__lt__(y) <==> x<y """
        pass

    def __mod__(self, y):  
        """ x.__mod__(y) <==> x%y """
        pass

    def __mul__(self, n):  
        """ x.__mul__(n) <==> x*n """
        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 __ne__(self, y):  
        """ x.__ne__(y) <==> x!=y """
        pass

    def __repr__(self):  
        """ x.__repr__() <==> repr(x) """
        pass

    def __rmod__(self, y):  
        """ x.__rmod__(y) <==> y%x """
        pass

    def __rmul__(self, n):  
        """ x.__rmul__(n) <==> n*x """
        pass

    def __sizeof__(self):  
        """ S.__sizeof__() -> size of S in memory, in bytes """
        pass

    def __str__(self):  
        """ x.__str__() <==> str(x) """
        pass

str
str

列表

list 创建列表,将其他元素装换成字符串

#创建列表
li = [11, 22, 33, 44]
li = list()
li = list([11, 22, 33, 44])

列表转换

以字符串转换成列表

#循环列表每个元素
s1= "李露"
#for循环输出字符 ==> 可迭代
l1 = list(s1)
print(l1)

['', '']

元组转换列表

t2 = ("alex", "sam", "eric")#元组
new_list = list(t2)
print(new_list)

['alex', 'sam', 'eric']
>>>

字典转换列表

dic = {'k1':"alex", 'k2':"eric"}
new_list1 = (dic.keys())
print(new_list1)

['k1', 'k2']
>>>

dic = {'k1':"alex", 'k2':"eric"}
new_list2 = (dic.values())
print(new_list2)

['alex', 'eric']
>>>

dic = {'k1':"alex", 'k2':"eric"}
new_list3 = (dic.itmes())
print(new_list3)

[('k1', 'alex'), ('k2', 'eric')])
>>>

元素集合

name = "alex"
age = 18

name_list = ["eric", "alex", "tony"]

#索引
print(name_list[0])
#切片

print(name_list[0:2])
print(name_list[2:len(name_list])
#for循环

for i in name_list:
    print(i)
#append追加
name_list = ["alex","eric","tony"]
name_list.append('seven')
print(name_list)
>>>["alex","eric","tony", "seven"]

#count计算个数
name_list = ["alex","eric","tony,"seven","seven","seven"]
print(name_list.count('seven')) 
>>>3
#expend添加列表
name_list = ["alex", "eric"]
temp = ["tony", "seven"]
print(name_list.expend(temp))
>>>["alex", "eric","tony", "seven"]

#添加元组字典进入列表
new_list = ["alex", "eric"]
temp = ("李", "露")
print(name.expend(temp))
>>>["alex","eric","李","露"]
#index索引 name_list = ["alex", "eric","tony", "seven"] print(name_list.index("alex")) >>>0 #insert指定索引插入数据 name_list = ["alex", "eric","tony", "seven"] print(name_list.insert(1, "guy")) >>>["alex","guy", "eric","tony", "seven"]
#pop移除列表最后一个元素,并赋给另一列表,默认移除尾部数据
name_list = ["alex", "eric", "tony", "seven"]
a1 = name_list.pop()
print(name_list)
print(a1)
>>>seven

#remove移除从左边第一个找到的元素
name_list = ["alex", "eric", "tony", "seven"]
name_list.remove('seven')
>>>["alex", "eric", "tony"]

#reverse翻转列表元素
name_list = ["alex", "eric", "tony", "seven"]
print(name_list.reverse())
>>>["seven","tony","eric","alex"]
#sort排序
name_list = ["alex", "eric", "tony", "seven"]
print(name_list.sort("seven"))
>>> ["alex", "eric", "tony"]
#del删除指定索引元素
name_list = ["alex", "eric", "tony"]
del name_list[1]
print(name_list)
>>>["alex",  "tony"]

name_list = ["alex", "eric", "tony"]
del name_list[1:3]
print(name_list)
>>>["alex"]

索引与切片  

#索引
li = ["alex", "eric", "seven", 123]
new_li = li[2]
>>>seven

#切片
li = ["alex", "eric", "seven", 123]
new_li = li[2:3]
>>>['seven'] #生成只有一个元素的列表
#列表中range的切片
lstRange = range(101) result = lstRange[2::2] print (result) >>> range(2, 101, 2)

列表的多层嵌套

li = ["alex", "eric", "seven", 123]
li = ["alex", 123, {"k1":"v1", "k2":{"vv":123, "li":456}}]

li[2] =  {"k1":"v1", "k2":{"vv":123, "li":456}}
li[2]['k2'] = {"vv":123, "li":456}
li[2]['k2']["vv"] = 123

li = ["alex", 123, {"k1":"v1", "k2":{"vv":(11, 22, 123), "li":456}}]
li[2]['k2']["vv"][2] = 123

 元祖

创建元组

#创建元组
t = (11,22,33)
t = tuple((11, 22, 33,))

#元组嵌套
t = tuple( [] {} )#字符串,列表,字典
#count, 计算元素出现的次数
name_tuple = ("alex", "eric", "seven")
print(name_tuple.count('alex'))
>>>1

#index获取指定元素的索引位置
print(name_tuple.index(‘alex'))
>>>0
name_tuple = ("alex", "eric")
#索引
print(name_tuple[0])
>>>alex

#长度len
print(name_tuple[len(name_tuple) -1])
>>>alex

#切片
print(name_tuple[0:1])

#for循环
for i in name_tuple:
     print(i)
#嵌套(元组的元素不可修改)
t = (11, 22, 33)
t = (11 ,22, ["alex", {"k1":"v1"}])
t[2][1]['k1']

#元组中列表元素的修改
t = (11 ,22, ["alex", {"k1":"v1"}])
t2 =["alex", {"k1":"v1"}]
t[2].append('xxx')
print(t)
>>>t = (11 ,22, ["alex", {"k1":"v1"},'xxx'])

#元组中字典元素修改
t = (11, 22, ["alex", {"k1":"v1"}])
t[2][1]['k2'] = 123
t[2][1].update({'k2':123})
print(t)

>>>(11, 22,["alex",{"k2":123, "k1":"v1"}])
lass 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__
        """ 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, y): # real signature unknown; restored from __doc__
        """ x.__add__(y) <==> x+y """
        pass

    def __contains__(self, y): # real signature unknown; restored from __doc__
        """ x.__contains__(y) <==> y in x """
        pass

    def __eq__(self, y): # real signature unknown; restored from __doc__
        """ x.__eq__(y) <==> x==y """
        pass

    def __getattribute__(self, name): # real signature unknown; restored from __doc__
        """ x.__getattribute__('name') <==> x.name """
        pass

    def __getitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__getitem__(y) <==> x[y] """
        pass

    def __getnewargs__(self, *args, **kwargs): # real signature unknown
        pass

    def __getslice__(self, i, j): # real signature unknown; restored from __doc__
        """
        x.__getslice__(i, j) <==> x[i:j]
                   
                   Use of negative indices is not supported.
        """
        pass

    def __ge__(self, y): # real signature unknown; restored from __doc__
        """ x.__ge__(y) <==> x>=y """
        pass

    def __gt__(self, y): # real signature unknown; restored from __doc__
        """ x.__gt__(y) <==> x>y """
        pass

    def __hash__(self): # real signature unknown; restored from __doc__
        """ x.__hash__() <==> hash(x) """
        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): # real signature unknown; restored from __doc__
        """ x.__iter__() <==> iter(x) """
        pass

    def __len__(self): # real signature unknown; restored from __doc__
        """ x.__len__() <==> len(x) """
        pass

    def __le__(self, y): # real signature unknown; restored from __doc__
        """ x.__le__(y) <==> x<=y """
        pass

    def __lt__(self, y): # real signature unknown; restored from __doc__
        """ x.__lt__(y) <==> x<y """
        pass

    def __mul__(self, n): # real signature unknown; restored from __doc__
        """ x.__mul__(n) <==> x*n """
        pass

    @staticmethod # known case of __new__
    def __new__(S, *more): # real signature unknown; restored from __doc__
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        pass

    def __ne__(self, y): # real signature unknown; restored from __doc__
        """ x.__ne__(y) <==> x!=y """
        pass

    def __repr__(self): # real signature unknown; restored from __doc__
        """ x.__repr__() <==> repr(x) """
        pass

    def __rmul__(self, n): # real signature unknown; restored from __doc__
        """ x.__rmul__(n) <==> n*x """
        pass

    def __sizeof__(self): # real signature unknown; restored from __doc__
        """ T.__sizeof__() -- size of T in memory, in bytes """
        pass

tuple
tuple

 字典

创建字典:

#字典的每个元素都是 键值对
user_info = {
        "name" : "alex", 
        "age" : 73   
        "gender" : 'M'
}   
#索引
user_info = {
        "name" : "alex", 
        "age" : 73   
        "gender" : 'M'
}   

print(user_info["name"])
>>>alex

#循环,默认值输出key
for i in user_info:
    print(i)
>>>"name"
        "age"
        "gender"


#获取多有键
for i in user_info.keys()

print(user_info.keys())
>>>dict_keys(["name", "age", "gender"])

#获取多有值
for i in user_info.values()

print(user_info.values())
>>>dict_values(["alex", "M", "73"])

#获取多有键值对
for k,v in user_info.items()
print(k)
print(v)

print(user_info.itmes())
>>>dict_items(["name" : "alex", "age" : 73, "gender" : 'M'])
user_info = {"name" : "alex", "age": 73, "gender": "M"}

#get 根据key获取值,如果可以不存在,可以指定一个默认值
val = user_info.get('age')
print(val)
>>>73

#索引取值时,key不存在,报错
print(user_info['age'])
>>>73

#has_key 检查指点中指定key是否存在
ret = 'age' in user_info.key()
print(ret)

#update
test = {"a1":123, "a2":456}
user_info.update(test)
>>>{"name" : "alex", "age": 73, "gender": "M", "a1" : 123, "a2" : 456}
#用fromkeys创建字典
@staticmethod 
    def fromkeys(*args, **kwargs): 
        """ Returns a new dict with keys from iterable and values equal to value. """
 
#方法,无@staticmethod,使用:对象. 方法 dic.get('key')
#方法,有@staticmethod,使用:类. 方法 dict.fromkeys([key1, key2...]value)

dic = {'k1':123, 'k2': 456, 'k4': 111}
m = dic.get('k2')
print(m)
>>>456

n = dict.fromkeys(['k1', 'k2', 'k3'], "alex")
print(n)
>>>{'k2': 'alex', 'k3': 'alex', 'k1': 'alex'}
dic = dict.fromkeys(['k1', 'k2', 'k3'], []) #fromkeys生成的'k1', 'k2', 'k3'指向相同的“[]”
print(dic)
>>>{'k1': [], 'k2': [], 'k3': []}

dic['k1'].append('x') #由于'k1', 'k2', 'k3'指向相同的“[]”,因此追加后values所在“[]”地址也相同
print(dic)
>>>{'k1': ['x'], 'k2': ['x'], 'k3': ['x']}
#del 删除指定索引的键值对
test = {"a1" : 123, "a2" : 456}
del test['a1']
print(test)
>>>{"a2" : 456}
#创建字典
a = {"k1":123} a = dict{k1 = 123, k2 = 456} print(a) >>>{k1 = 123, k2 = 456} #列表转字典,需加入enumerate生成key li = [11, 22, 33] new_dict = dic(enumerate(li, 1)) print(new_dict) >>>{1: 11, 2:22, 3:33}

enumrate

class enumerate(object):
    enumerate(iterable[, start]) -> iterator for index, value of iterable. (0, seq[0]), (1, seq[1]), (2, seq[2]), ...

 为可迭代的对象添加序号

 li = [11,22,33]
for k,v in enumerate(li, 1):
     print(k,v)
#enumerate自动生成一列,默认“0”自增1

 使用实例

li = ["商品1", "商品2", "商品3", "商品4"]
for key in item in enumerate(li, 1):
    print(key, item)

inp = input("请输入商品编号: ")#系统默认输入'str'
#字符串转换成int
inp_num = int(inp)

print(li[inp_num-1])
for i,j in enumerate(('a','b','c')):
    print i,j

>>>
0 a
1 b
2 c

for i,j in enumerate({'a':1,'b':2}):
    print i,j

>>>
0 a
1 b

for i,j in enumerate('abc'):
    print i,j

>>>
0 a
1 b
2 c
goodsDic = {'computer':5000,'mouse':200}
goodsLst =  goodsDic.keys()
for i,j in enumerate(goodsLst):

    print ('%-5s%-10s%-10s'%(i,j,goodsDic[j]))

>>>
0    computer  5000      
1    mouse     200       

range和xrange(python2.7)

指定范围,生成指定的数字

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]  
#range, xrange
#range 用获取指定范围内的数range(0,1000)
#xrange 用获取指定范围内的数xrange(1, 1000)    
#py2.7
for i in xrange(1,1000):
    print (i)

#py3, range等同于 py2.7 xrange
print(range(1,10))
for i in range(1,10,2):#1-10之间,步长为2
    print(i)
>>>1,3,5,7,9

for i in range(10,1,-1)
    print(i)
>>>10,9,8,7,6,5,4,3,2

#利用len获取列表长度,
li  = ["alex", "eric"]
le = len(li)#2
#用for循环获取索引 和 元素
for i in range(0, le):
    print(i,li[i])
>>>0 alex
   1 eric

字节

bytes (“字节”)

class bytes(object):
    """
    bytes(iterable_of_ints) -> bytes
    bytes(string, encoding[, errors]) -> bytes
    bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
    bytes(int) -> bytes object of size given by the parameter initialized with null bytes
    bytes() -> empty bytes object
    
    Construct an immutable array of bytes from:
      - an iterable yielding integers in range(256)
      - a text string encoded using the specified encoding
      - any object implementing the buffer API.
      - an integer
    """

 for循环输出字节

for b in bytes_list: #进入for循环以默认10进制表示
   print(b)        #输出以10进制字节表示字符串
   print(bin(b))   #bin() 十进制转为二进制 
#python2.7
neme = "李露" 
for i in name:
    print(i)
230
157
142
233
156
178
>>>
#Python3.5 for 循环,循环的每一个元素是“字符”
name = "李露" for i in name: print(i) >>>李 露

字符串转换字节

#bytes(string, encoding[, errors]) -> bytes
#bin(*args, **kwargs):Return the binary representation of an integer.
bytes_list = bytes (“字符串”, encoding = 'UTF-8') #UTF-8 ==> 3字节, gbk ==> 2字节
print(bytes_list) #默认每一个字节都是16进制表示

字符串转成UTF-8(3个字节)

name = "李露"

for i in name:
    print(i)
    print(bytes(i,encoding = 'utf-8'))#转为utf-8编码(3个字节),1个汉字,3个字节,一个字节8位;encoding = 'utf-8' 不同的编码编程相应的字节   
                       #bytes字符转字节
  bytes_list = bytes(i, encoding = 'utf-8')#以每个汉字的3个字节为元素,生成列表

for
b in bytes_list: #for循环字节默认10进制 #输出每一个字节默认16进制 print(b,bin(b))#转换为10进制的数字
 
>>>
  b
'xe6x9dx8e' #utf-8字节(16进制) “李露” :字节/字节/字节/字节/字节/字节 用16进制表示的二进制
  230 0b11100110 #10进制 / 2进制 01010101/01010101/01010101/01010101/01010101/01010101
  157 0b10011101  
  142 0b10001110  
  

  b
'xe9x9cxb2'
  233 0b11101001
  156 0b10011100
  178 0b10110010

字符串转成gbk(2个字节)

name = "李露"

for i in name:
    print(i)
    print(bytes(i,encoding = 'gbk'))#gbk编码,1个汉字,2个字节,一个字节8位
    bytes_list = bytes(i, encoding = 'gbk')
    for b in bytes_list:
        #字节默认16进制
        #输出每一个字节默认10进制
        print(b,bin(b)
>>>
李
b'xc0xee'
192 0b11000000
238 0b11101110
露
b'xc2xb6'
194 0b11000010
182 0b10110110

字节转换为字符

x = str(bytes, encoding = 编码)

  创建字符串

  转换成字符串,字节,编码

字符转换字节

m = bytes(str, encoding = 编码)

  创建字节

  转换字节,字符串,要编程什么编码类型的字节

  

a = "李露"
#将字符串转成字节
b1= bytes(a, encoding = 'utf-8')
print(b1)
b2= bytes(a, encoding = 'gbk')
print(b2)

b'xe6x9dx8exe9x9cxb2'
b'xc0xeexc2xb6'
>>>

#将字节转成字符串
new_str1 = str(b1, encoding = 'utf-8')
print(new_str1)

new_str2 = str(b1, encoding = 'gbk')
print(new_str2)

李露
李露
>>>

长度 len()

Python2.7
a = "李露"
print(len(a))

>>>6

#Python3.5
a = "李露"
print(len(a))

>>>2

内存地址 id()

a = "李露"
print(id(a))

>>>38148736

数据基本类型函数小结:

原文地址:https://www.cnblogs.com/Sam-r/p/5482786.html