Python 基礎部分-2

Pycharm

PyCharm是一種Python IDE,帶有一整套能夠幫助用戶在使用Python語言開發時提升其效率的工具,好比調試、語法高亮、Project管理、代碼跳轉、智能提示、自動完成、單元測試、版本控制。此外,該IDE提供了一些高級功能,以用於支持Django框架下的專業Web開發。python

 

解釋器設定git

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

 

#!/usr/bin/env pythonapi

# -*- coding:utf-8 -*- (適用python2.7)數組

from __future__ import division app

 

文字設定框架

file > setting > Editor > color and font > font > save as > 選擇「size」less

 

 

更換編譯器版本python2.7

file > setting > project interpreter > 選擇已安裝的版本ide

 

運行程序

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\t999" 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
'\xe6\x9d\x8e' #utf-8字節(16進制) 「李露」 :字節/字節/字節/字節/字節/字節 用16進製表示的二進制
  230 0b11100110 #10進制 / 2進制 01010101/01010101/01010101/01010101/01010101/01010101
  157 0b10011101  
  142 0b10001110  
  

  b
'\xe9\x9c\xb2'
  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'\xc0\xee'
192 0b11000000
238 0b11101110
露
b'\xc2\xb6'
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'\xe6\x9d\x8e\xe9\x9c\xb2'
b'\xc0\xee\xc2\xb6'
>>>

#將字節轉成字符串
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

 

數據基本類型函數小結:

 

 

 

 

 

相關文章
相關標籤/搜索