Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.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_Loops_For Loop_Printf_Line - Fatal编程技术网

Python for循环-迭代还是不迭代?

Python for循环-迭代还是不迭代?,python,loops,for-loop,printf,line,Python,Loops,For Loop,Printf,Line,我正在使用Python编写一个基于特定指令集的刽子手游戏。我特别需要使用for循环,以便用下划线替换单词中的所有字母,事实上,我成功地做到了这一点。然而,我有一个小问题,我的单词中的每个字母都会有一行新的下划线。有办法摆脱这个吗?有人能告诉我我的逻辑有什么问题吗 word = "test" def createBlank(word): for letter in word: blanks = '_' * len(word) print(blanks)

我正在使用Python编写一个基于特定指令集的刽子手游戏。我特别需要使用
for
循环,以便用下划线替换单词中的所有字母,事实上,我成功地做到了这一点。然而,我有一个小问题,我的单词中的每个字母都会有一行新的下划线。有办法摆脱这个吗?有人能告诉我我的逻辑有什么问题吗

word = "test"

def createBlank(word):
    for letter in word:
        blanks = '_' * len(word)
        print(blanks)
我的结果如你所想:

>word
“测试”
>>>创建空白(word)

____#您正在重复打印
空格
以获得
word
中的字符数。只需将
打印(空白)
移动到
外部,即可进行
循环:

word = "test"

def createBlank(word):
    for letter in word:
            blanks = '_' * len(word)
    print(blanks)
演示:

>>> createBlank(word)
____
但是,为什么需要一个
循环来打印下划线乘以
word
len
,您可以这样做:

word = "test"

def createBlank(word):
    blanks = '_' * len(word)
    print(blanks)

实际上,您使用这个“*len(word)”是错误的,因为它是在循环中运行的,所以它会打印多次

试试这个

word = "test"

def createBlank(word):
    for letter in word:
        blanks = '_'
        print blanks,
A这辆车跑得更好

from __future__ import print_function # needs to be first statement in file
word = "test"

def createBlank(word):
    for letter in word:
        print('_', end='')
createBlank(word)

是否需要
循环的
?定义
空格
变量4次?不,不是。OP每次迭代都会给
blank
相同的值。@KevinGuan…不…我只是更新我的答案在这一点上,
blank
甚至不需要,他可以让方程计算成
print
like
print('.*len(word))
@AustinWBryan…我不喜欢这种方法,因为我喜欢可读性而不是代码压缩