收集的幾個Python小技巧分享
獲得當(dāng)前機(jī)器的名字:
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'
獲取當(dāng)前工作路徑:
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)
寫平臺獨(dú)立的代碼必須使用的:
>>> import os
>>> os.pathsep
';'
>>> os.sep
'\\'
>>> os.linesep
'\r\n'
相關(guān)文章
關(guān)于數(shù)據(jù)分析之滾動窗口pandas.DataFrame.rolling方法
Pandas庫中的rolling方法是數(shù)據(jù)處理中常用的功能,它允許用戶對數(shù)據(jù)進(jìn)行滾動窗口(滑動窗口)操作,通過指定窗口大小,可以使用不同的聚合函數(shù)對窗口內(nèi)的數(shù)據(jù)進(jìn)行計算,例如最大值、最小值、平均值、中位數(shù)等,此外,rolling方法還可以計算方差、標(biāo)準(zhǔn)差、偏度、峰度2024-09-09
python實現(xiàn)在windows下操作word的方法
這篇文章主要介紹了python實現(xiàn)在windows下操作word的方法,涉及Python操作word實現(xiàn)打開、插入、轉(zhuǎn)換、打印等操作的相關(guān)技巧,非常具有實用價值,需要的朋友可以參考下2015-04-04
python pprint模塊中print()和pprint()兩者的區(qū)別
這篇文章主要介紹了python pprint模塊中print()和pprint()兩者的區(qū)別,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02

