收集的几个Python小技巧分享

作者:junjie 时间:2023-06-14 01:54:01 

获得当前机器的名字:


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,小技巧
0
投稿

猜你喜欢

  • django foreignkey外键使用的例子 相当于left join

    2021-04-17 15:52:33
  • 用vscode开发python的步骤详解

    2023-11-10 11:39:22
  • Docker创建Mysql容器的简单步骤

    2024-01-28 20:20:40
  • javascript开发中使用onpropertychange,oninput事件解决onchange事件的不足

    2024-04-26 17:14:12
  • Python中的下划线详解

    2021-10-24 14:17:32
  • Python爬虫实战之虎牙视频爬取附源码

    2021-04-02 01:23:27
  • vue项目中data数据之间互相访问的实现

    2024-05-28 15:51:43
  • Access下如何使用通用对话框

    2008-11-20 16:41:00
  • Go语言实现选择法排序实例

    2024-04-25 15:29:33
  • Python3如何使用tabulate打印数据

    2021-04-17 15:09:26
  • 浅谈innodb_autoinc_lock_mode的表现形式和选值参考方法

    2024-01-12 17:22:55
  • PHP的PDO大对象(LOBs)

    2023-06-07 06:45:36
  • [机器视觉]使用python自动识别验证码详解

    2021-09-12 03:24:36
  • jquery实现点击页面计算点击次数

    2024-04-16 10:33:17
  • Perl中的符号 ->;、=>; 和 :: 分别表示什么意思?

    2022-11-28 14:38:48
  • 在js中的replace方法详解

    2007-08-21 15:47:00
  • Python直接赋值及深浅拷贝原理详解

    2021-11-23 02:24:18
  • Git如何修改已提交的commit注释

    2023-10-04 02:17:54
  • python 提取tuple类型值中json格式的key值方法

    2022-10-04 20:05:32
  • Python3中多线程编程的队列运作示例

    2022-06-15 23:27:49
  • asp之家 网络编程 m.aspxhome.com