收集的几个Python小技巧分享

yipeiwu_com6年前Python基础

获得当前机器的名字:

复制代码 代码如下:

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)

获取系统的临时目录:

复制代码 代码如下:

os.getenv('TEMP')

字符串与int,long,float的转化:

python的变量看起来是没有类型的,其实是有变量是有类型的。

使用locale模块下的atoi和atof来将字符串转化为int或float,或者也可以直接使用int(),float(),str()来转化。以前的版本中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的转化:

复制代码 代码如下:

# 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'

相关文章

Python中List.count()方法的使用教程

 count()方法返回obj出现在列表的次数。 语法 以下是count()方法的语法: list.count(obj) 参数   &nbs...

跟老齐学Python之做一个小游戏

在讲述有关list的时候,提到做游戏的事情,后来这个事情一直没有接续。不是忘记了,是在想在哪个阶段做最合适。经过一段时间学习,看官已经不是纯粹小白了,已经属于python初级者了。现在就...

对Python 2.7 pandas 中的read_excel详解

导入pandas模块: import pandas as pd 使用import读入pandas模块,并且为了方便使用其缩写pd指代。 读入待处理的excel文件: df =...

Python简单计算数组元素平均值的方法示例

Python简单计算数组元素平均值的方法示例

本文实例讲述了Python简单计算数组元素平均值的方法。分享给大家供大家参考,具体如下: Python 环境:Python 2.7.12 x64 IDE :  &nb...

Python实现的计算马氏距离算法示例

Python实现的计算马氏距离算法示例

本文实例讲述了Python实现的计算马氏距离算法。分享给大家供大家参考,具体如下: 我给写成函数调用了 python实现马氏距离源代码: # encoding: utf-8 fro...