python环境变量设置 python类型转换 int str chr ord

2015-08-13 20:16:00
admin
原创 4079
摘要:python环境变量设置 python类型转换 int str chr ord

一、python环境变量设置

system()、popen()、fork()、execv()等函数会使用环境变量。


获取环境变量:最好使用函数,当变量不存在读字典会抛异常,函数会返回None。

os.getenv('PATH')

os.environ['PATH']


设置环境变量:只能直接写字典,函数有些平台不支持。

os.environ['APP'] = 'python'

os.putenv('APP', 'python')


二、python类型转换

int(x [,base]),将参数转换为整数,参数可以是字符串、整数、浮点数;

long(x [,base]),将参数转换为长整数,参数可以是字符串、整数、浮点数;
float(x),将参数转换为浮点数,参数可以是字符串、整数、浮点数;
complex(real [,imag]),创建复数;

print int('11', 2),输出3

print int('11', 10),输出11


str(x),对象转换为字符串;

print type(str(100)),输出<type 'str'>


repr(x),对象转换为表达式字符串;
eval(str),计算字符串中的有效表达式;
tuple(s),序列转换为元组;
list(s),序列转换为列表;


chr(x),整数转换为字符;

unichr(x),整数转换为unicode字符;

hex(x),整数转换为十六进制字符串;
oct(x),整数转换为八进制字符串;

print chr(0x31),输出1


ord(x),字符转换为整数;

print ord('a'),输出97


字符串转换成16进制:

def str_to_hex(s):
    return ''.join(['%02x'%(ord(c)) for c in s])

16进制转换成字符串:
def hex_to_str(s):
    length = len(s)/2
    return ''.join([chr(iv) for iv in [int(s[pos*2:pos*2+2],16) for pos in range(0,length)]])

发表评论
评论通过审核之后才会显示。