1. 程式人生 > >python學習【第三篇】基本數據類型

python學習【第三篇】基本數據類型

ini ati 絕對值 ef6 ict trunc any 替換 不包含

Number(數字)

int(整型)

  在32位機器上,整數的位數為32位,取值範圍為-2**31~2**31-1,即-2147483648~2147483647
  在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
View Code

1.1 數字類型的創建

a=10
b=a
b=666
 
print(a)#10
print(b)#666

1.2 Number類型轉換

var1=3.14
var2=5
var3=int(var1)
var4=float(var2)
 
print(var3,var4)

技術分享
abs(x)    返回數字的絕對值,如abs(-10) 返回 10
# ceil(x)    返回數字的上入整數,如math.ceil(4.1) 返回 5
# cmp(x, y)    如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1
# exp(x)    返回e的x次冪(ex),如math.exp(1) 返回2.718281828459045
# fabs(x)    返回數字的絕對值,如math.fabs(-10) 返回10.0
# floor(x)    返回數字的下舍整數,如math.floor(4.9)返回 4
# log(x)    如math.log(math.e)返回1.0,math.log(100,10)返回2.0
# log10(x)    返回以10為基數的x的對數,如math.log10(100)返回 2.0
# max(x1, x2,...)    返回給定參數的最大值,參數可以為序列。
# min(x1, x2,...)    返回給定參數的最小值,參數可以為序列。
# modf(x)    返回x的整數部分與小數部分,兩部分的數值符號與x相同,整數部分以浮點型表示。
# pow(x, y)    x**y 運算後的值。
# round(x [,n])    返回浮點數x的四舍五入值,如給出n值,則代表舍入到小數點後的位數。
# sqrt(x)    返回數字x的平方根,數字可以為負數,返回類型為實數,如math.sqrt(4)返回 2+0j

PY內置數學函數
python內置數學函數

字符串

字符串是以單引號或雙引號"括起來的任意文本,比如‘abc‘"123"等等。

請註意,‘‘""本身只是一種表示方式,不是字符串的一部分,因此,字符串‘abc‘只有abc這3個字符。如果本身也是一個字符,那就可以用""括起來,比如"I‘m OK"包含的字符是Im,空格,OK這6個字符。

創建字符串

var1 = ‘Hello World!‘
var2 = "Python RAlvin"

 

對應的操作

# 1   * 重復輸出字符串
print(‘hello‘*2)
 
# 2 [] ,[:] 通過索引獲取字符串中字符,這裏和列表的切片操作是相同的,具體內容見列表
print(‘helloworld‘[2:])
 
# 3 in  成員運算符 - 如果字符串中包含給定的字符返回 True
print(‘el‘ in ‘hello‘)
 
# 4 %   格式字符串
print(‘alex is a good teacher‘)
print(‘%s is a good teacher‘%‘alex‘)
 
 
# 5 +   字符串拼接
a=‘123‘
b=‘abc‘
c=‘789‘
d1=a+b+c
print(d1)
# +效率低,該用join
d2=‘‘.join([a,b,c])
print(d2)

 

技術分享
# string.capitalize()                                  把字符串的第一個字符大寫
# string.center(width)                                 返回一個原字符串居中,並使用空格填充至長度 width 的新字符串
# string.count(str, beg=0, end=len(string))            返回 str 在 string 裏面出現的次數,如果 beg 或者 end 指定則返回指定範圍內 str 出現的次數
# string.decode(encoding=‘UTF-8‘, errors=‘strict‘)     以 encoding 指定的編碼格式解碼 string,如果出錯默認報一個 ValueError 的 異 常 , 除 非 errors 指 定 的 是 ‘ignore‘ 或 者‘replace‘
# string.encode(encoding=‘UTF-8‘, errors=‘strict‘)     以 encoding 指定的編碼格式編碼 string,如果出錯默認報一個ValueError 的異常,除非 errors 指定的是‘ignore‘或者‘replace‘
# string.endswith(obj, beg=0, end=len(string))         檢查字符串是否以 obj 結束,如果beg 或者 end 指定則檢查指定的範圍內是否以 obj 結束,如果是,返回 True,否則返回 False.
# string.expandtabs(tabsize=8)                         把字符串 string 中的 tab 符號轉為空格,tab 符號默認的空格數是 8。
# string.find(str, beg=0, end=len(string))             檢測 str 是否包含在 string 中,如果 beg 和 end 指定範圍,則檢查是否包含在指定範圍內,如果是返回開始的索引值,否則返回-1
# string.index(str, beg=0, end=len(string))            跟find()方法一樣,只不過如果str不在 string中會報一個異常.
# string.isalnum()                                     如果 string 至少有一個字符並且所有字符都是字母或數字則返回 True,否則返回 False
# string.isalpha()                                     如果 string 至少有一個字符並且所有字符都是字母則返回 True,否則返回 False
# string.isdecimal()                                   如果 string 只包含十進制數字則返回 True 否則返回 False.
# string.isdigit()                                     如果 string 只包含數字則返回 True 否則返回 False.
# string.islower()                                     如果 string 中包含至少一個區分大小寫的字符,並且所有這些(區分大小寫的)字符都是小寫,則返回 True,否則返回 False
# string.isnumeric()                                   如果 string 中只包含數字字符,則返回 True,否則返回 False
# string.isspace()                                     如果 string 中只包含空格,則返回 True,否則返回 False.
# string.istitle()                                     如果 string 是標題化的(見 title())則返回 True,否則返回 False
# string.isupper()                                     如果 string 中包含至少一個區分大小寫的字符,並且所有這些(區分大小寫的)字符都是大寫,則返回 True,否則返回 False
# string.join(seq)                                     以 string 作為分隔符,將 seq 中所有的元素(的字符串表示)合並為一個新的字符串
# string.ljust(width)                                  返回一個原字符串左對齊,並使用空格填充至長度 width 的新字符串
# string.lower()                                       轉換 string 中所有大寫字符為小寫.
# string.lstrip()                                      截掉 string 左邊的空格
# string.maketrans(intab, outtab])                     maketrans() 方法用於創建字符映射的轉換表,對於接受兩個參數的最簡單的調用方式,第一個參數是字符串,表示需要轉換的字符,第二個參數也是字符串表示轉換的目標。
# max(str)                                             返回字符串 str 中最大的字母。
# min(str)                                             返回字符串 str 中最小的字母。
# string.partition(str)                                有點像 find()和 split()的結合體,從 str 出現的第一個位置起,把 字 符 串 string 分 成 一 個 3 元 素 的 元 組 (string_pre_str,str,string_post_str),如果 string 中不包含str 則 string_pre_str == string.
# string.replace(str1, str2,  num=string.count(str1))  把 string 中的 str1 替換成 str2,如果 num 指定,則替換不超過 num 次.
# string.rfind(str, beg=0,end=len(string) )            類似於 find()函數,不過是從右邊開始查找.
# string.rindex( str, beg=0,end=len(string))           類似於 index(),不過是從右邊開始.
# string.rjust(width)                                  返回一個原字符串右對齊,並使用空格填充至長度 width 的新字符串
# string.rpartition(str)                               類似於 partition()函數,不過是從右邊開始查找.
# string.rstrip()                                      刪除 string 字符串末尾的空格.
# string.split(str="", num=string.count(str))          以 str 為分隔符切片 string,如果 num有指定值,則僅分隔 num 個子字符串
# string.splitlines(num=string.count(‘\n‘))            按照行分隔,返回一個包含各行作為元素的列表,如果 num 指定則僅切片 num 個行.
# string.startswith(obj, beg=0,end=len(string))        檢查字符串是否是以 obj 開頭,是則返回 True,否則返回 False。如果beg 和 end 指定值,則在指定範圍內檢查.
# string.strip([obj])                                  在 string 上執行 lstrip()和 rstrip()
# string.swapcase()                                    翻轉 string 中的大小寫
# string.title()                                       返回"標題化"的 string,就是說所有單詞都是以大寫開始,其余字母均為小寫(見 istitle())
# string.translate(str, del="")                        根據 str 給出的表(包含 256 個字符)轉換 string 的字符,要過濾掉的字符放到 del 參數中
# string.upper()                                       轉換 string 中的小寫字母為大寫
python的內置方法

python學習【第三篇】基本數據類型