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

Python密码生成器for循环打印逐行换行 如何实现字符并排连续输出

问题原因

你在循环中每次生成单个字符就调用print()输出,Python的print()函数默认会在输出内容末尾添加换行符\n,因此每个字符都会单独占一行。

修改方案

有两种常用修改方式,第一种更推荐:

方案1:拼接完整密码后一次性输出

预先初始化一个空字符串存储密码,循环过程中把生成的字符追加到字符串中,循环结束后统一打印完整密码。
仅需要修改生成密码的对应代码块即可:

if digit_count >= 5 and digit_count <= 35:
    password = ""
    for i in range(digit_count):
        password += random.choice(char_list)
    print(password)

方案2:修改print的默认换行规则

给print()添加end=""参数,取消默认追加的换行符,让字符连续输出:

if digit_count >= 5 and digit_count <= 35:
    for i in range(digit_count):
        password = random.choice(char_list)
        print(password, end="")
    # 最后加一个换行,避免后续控制台输出和密码拼接在同一行
    print()

完整修改后代码

注:原代码中的拼写错误sequre已修正为正确的secure

import random

options = '1234567890!@#$%^&*()`~-_=+\|]}[{\'";:/?.>,<QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm'
char_list = tuple(options)

print("""Password checker
This either checks your password or creates a secure password.
Your commands are "create password" and "check password"""")

command = str(input('Type your command: '))

if command.lower() == 'create password':
    digit_count = int(input('How many digits do you want your password to be? (Must be more than five and under 35): '))

    if digit_count >= 5 and digit_count <= 35:
        password = ""
        for i in range(digit_count):
            password += random.choice(char_list)
        print(password)

    else:
        print('Bruh I told you to give more than 5 or under 35')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 16:48:03