1. 程式人生 > >python 字串和整數,浮點型互相轉換

python 字串和整數,浮點型互相轉換

轉載:http://www.cnblogs.com/chenfulin5/p/7813791.html

  • 在程式設計當中,經常要用到字串的互相轉換, 現在記錄 python 裡面的字串和整數是怎麼轉換的。

  • int(str) 函式將 符合整數的規範的字串 轉換成 int 型。

    num2 = "123";
    num2 = int(num1);
    print("num2: %d" % num2);
    '''
    輸出  num2: 123
    '''
  • float(str) 函式將 符合 浮點型 的規範的字串 轉換成 float 型。

    num1 = "123.12";
    num2 = float(num1);
    print("num2: %f" % num2);
    '''
    num2: 123.120000
    '''
  • str(num) 將 整數,浮點型轉換成 字串

    num = 123;
    mystr = str(num);
    print ("%s" % mystr);
    ''' 輸出 123   '''