You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3.9开发密码生成器报错write() argument must be str, not bytes

Python 2.7 代码迁移到 Python 3.9 修复方案

需要修改以下不兼容及语法错误点:

  • 移除Python2独有语法xrange,Python3中对应实现已合并到range函数
  • 修正字符串拼接符号笔误:将错误的+-替换为正确的拼接赋值符+=
  • 处理urlopen返回的bytes类型:读取远程内容后需调用decode('utf-8')转为字符串,才能写入文本模式打开的words.txt
  • 修正print函数语法:Python3中print为函数,格式化操作符%需要放在函数参数括号内部
  • 适配字符串拼接类型规则:数字不能直接和字符串拼接,需调用str()转为字符串类型
  • 修正特殊字符选择逻辑:调用choice(special_chars)随机选取单个特殊字符,而非直接拼接整个特殊字符列表

修复后完整代码如下:

from passwordmeter import test
from urllib.request import urlopen
from os.path import isfile 
from random import choice,randint

if not isfile('words.txt'):
    print('Downloading words.txt ...')
    url='https://raw.githubusercontent.com/dwyl/english-words/master/words.txt'
    with open('words.txt','w', encoding='utf-8') as f:
        f.write(urlopen(url).read().decode('utf-8'))

words=open('words.txt', 'r', encoding='utf-8').read().split("\n")
special_chars=['!','?']

def create_password(num_words=2, num_numbers=4, num_special=1):
    pass_str=''

    for _ in range(num_words):
        pass_str+=choice(words).lower().capitalize()
    for _ in range(num_numbers):
        pass_str+=str(randint(0,9))
    for _ in range(num_special):
        pass_str+=choice(special_chars)
    return pass_str
    
def main():
    pass_str=create_password()
    strength,_=test(pass_str)

    print('\nPassword: %s'%pass_str)
    print('Strength: %0.5f'%strength)

if __name__=='__main__':
    main()

内容的提问来源于stack exchange,提问作者novaks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 20:39:02