python中的encode()和decode()函数

字符串转二进制用decode
二进制转字符串用encode
举例:

msg="hello 世界你好"
print(msg)
print(msg.encode("utf-8"))
print(msg.encode("utf-8").decode("utf-8"))

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这段代码存在一些小问题,可以改进如下: 1. `random(1, 1000)` 应该改成 `range(1000)`,表示生成一个 0~999 的随机整数序列。 2. 在循环时可以使用 `for i in range(1000)`,这样可以避免使用 `i` 变量之前未定义的问题。 3. 发送数据时,最好使用 try...except...finally 结构来确保程序的健壮性。如果在发送数据时出现异常,可以通过 `except` 分支将异常信息输出到控制台,然后继续执行程序。最后通过 `finally` 分支关闭串口,释放资源。 综上,改进后的代码如下: ```python import serial import time import random # 打开串口 portx = "COM3" bps = 9600 timex = 5 ser = serial.Serial(portx, bps, timeout=timex) print("串口详情参数:", ser) try: # 循环写入 t6.txt for i in range(1000): num = random.randint(1, 1000) print(num) msg = "t6.txt=\"{}\"".format(num) ser.write(msg.encode("utf-8")) ser.write(b'\xff\xff\xff') # 发送标志 time.sleep(0.1) # 循环写入 t7.txt for i in range(1000): num = random.randint(1, 1000) print(num) msg = "t7.txt=\"{}\"".format(num) ser.write(msg.encode("utf-8")) ser.write(b'\xff\xff\xff') # 发送标志 time.sleep(0.1) # 循环写入 t8.txt for i in range(1000): num = random.randint(1, 1000) print(num) msg = "t8.txt=\"{}\"".format(num) ser.write(msg.encode("utf-8")) ser.write(b'\xff\xff\xff') # 发送标志 time.sleep(0.1) except Exception as e: print("---异常---:", e) finally: # 关闭串口 ser.close() ``` 注意:这段代码仅供参考,实际使用时还需根据具体需求进行修改和完善。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值