欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

收集的幾個Python小技巧分享

 更新時間:2014年11月22日 09:45:02   投稿:junjie  
這篇文章主要介紹了收集的幾個Python小技巧分享,如獲得當前機器的名字、獲取當前工作路徑、獲取系統(tǒng)的臨時目錄等,需要的朋友可以參考下

獲得當前機器的名字:

復制代碼 代碼如下:

def hostname():
        sys = os.name 
 
        if sys == 'nt': 
                hostname = os.getenv('computername') 
                return hostname 
 
        elif sys == 'posix': 
                host = os.popen('echo $HOSTNAME') 
                try: 
                        hostname = host.read() 
                        return hostname 
                finally: 
                        host.close()
        else: 
                return 'Unkwon hostname'

獲取當前工作路徑:

復制代碼 代碼如下:

import os
 
os.getcwd()

#or

#os.curdir just return . for current working directory.
#need abspath() to get full path.
os.path.abspath(os.curdir)

獲取系統(tǒng)的臨時目錄:

復制代碼 代碼如下:

os.getenv('TEMP')

字符串與int,long,float的轉(zhuǎn)化:

python的變量看起來是沒有類型的,其實是有變量是有類型的。

使用locale模塊下的atoi和atof來將字符串轉(zhuǎn)化為int或float,或者也可以直接使用int(),float(),str()來轉(zhuǎn)化。以前的版本中atoi和atof是在string模塊下的。

復制代碼 代碼如下:

s = "1233423423423423"
import locale
locale.atoi(s)
#1233423423423423
locale.atof(s)
#1233423423423423.0
int(s)
#1233423423423423
float(s)
#1233423423423423.0
str(123434)
"123434"

bytes和unicodestr的轉(zhuǎn)化:

復制代碼 代碼如下:

# bytes object 
 b = b"example" 
 
 # str object 
 s = "example" 
 
 # str to bytes 
 bytes(s, encoding = "utf8") 
 
 # bytes to str 
 str(b, encoding = "utf-8") 
 
 # an alternative method 
 # str to bytes 
 str.encode(s) 
 
 # bytes to str 
 bytes.decode(b)

寫平臺獨立的代碼必須使用的:


復制代碼 代碼如下:

>>> import os
>>> os.pathsep
';'
>>> os.sep
'\\'
>>> os.linesep
'\r\n'

相關文章

最新評論