Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何显示for循环中的整数和字母字符串_Python_String_Python 3.x_For Loop - Fatal编程技术网

Python 如何显示for循环中的整数和字母字符串

Python 如何显示for循环中的整数和字母字符串,python,string,python-3.x,for-loop,Python,String,Python 3.x,For Loop,我试图通过生成8个33到126之间的随机数来创建一个8个字符的密钥,然后将8个数字中的每一个转换为ASCII字符。我已经能够做到这一切: print('Eight-Character Key: ') for i in range(0,8): key = random.randint(33,126) key = chr(key) print(key,end='') 输出为: Eight-Character Key:

我试图通过生成8个33到126之间的随机数来创建一个8个字符的密钥,然后将8个数字中的每一个转换为ASCII字符。我已经能够做到这一切:

print('Eight-Character Key: ')    
for i in range(0,8):
            key = random.randint(33,126)
            key = chr(key)
            print(key,end='')
输出为:

Eight-Character Key: 
BAU78)E)
但理想情况下,我希望这一切都在同一条线上:

Eight-Character Key: BAU78) E)

您知道如何使用函数的
end
参数,这是一个显而易见的解决方案:

print('Eight-Character Key: ', end='')
#                              ^^^^^^
#                         no end-of-line after that

for i in range(0,8):
        key = random.randint(33,126)
        key = chr(key)
        print(key, end='')

print()
# ^^^^^
# end of line
还有一种更“蟒蛇式”的方法:

passwd = (chr(random.randint(33,126)) for _ in range(8))
print('Eight-Character Key:', "".join(passwd))


但是,请注意,无论您采用何种方式,它都不是非常安全的,因为Python对内存没有低级别的控制。因此,可以从内存转储访问生成的密码(有关可能的解决方法,请参阅)。除此之外,由于密码可能会显示在控制台上,因此在涉及的各种进程堆中,该密码可能也有许多副本。

结束
放在第一个
打印
语句之后

print('Eight-Character Key: ',end='')    
for i in range(0,8):
            key = random.randint(33,126)
            key = chr(key)
            print(key,end='')
其他方法-通过将键附加到字符串,然后
打印

k = ''
for i in range(0,8):
            key = random.randint(33,126)
            k += chr(key) 
print('Eight-Character Key: ',k,end='')