收集的几个Python小技巧分享

yipeiwu_com5年前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文件的读写和异常代码示例

一、从文件中读取数据 #!/usr/bin/env python with open('pi') as file_object: contents = file_object.r...

python判断一个对象是否可迭代的例子

如何判断一个对象是可迭代对象? 方法是通过collections模块的Iterable类型判断: >>> from collections import Iter...

Python批量更改文件名的实现方法

Python批量更改文件名的实现方法 前言: 由于后台数据有好多,但是文案提供过来的图片命名全部没有按照格式来命名,Python这么强大的语言,肯定是能够处理这个问题的,于是我就写了一个...

Python 判断奇数偶数的方法

以下实例用于判断一个数字是否为奇数或偶数: # -*- coding: UTF-8 -*- # Filename : test.py # Python 判断奇数偶数 # 如果是偶数除...

python正则表达式re之compile函数解析

re正则表达式模块还包括一些有用的操作正则表达式的函数。下面主要介绍compile函数。 定义: compile(pattern[,flags] ) 根据包含正则表达式的字符串创...