python技巧32[常用技巧集]


获得当前机器的名字:
来自:http://tony413.iteye.com/blog/395177

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 ' 

 

获取当前工作路径:
来自:http://www.cnblogs.com/Henrya2/archive/2009/01/16/1377284.html

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的转化:

来自:http://blog.csdn.net/yatere/article/details/6606316

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

 

 

完!
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值