for 循环 - 迭代还是不迭代?
for loop - to iterate or not to iterate?
我正在根据一组特定的说明使用 Python 编写刽子手游戏。我特别需要使用 for
循环来用下划线替换单词中的所有字母,事实上我已经成功地这样做了。但是我有一个小问题,我为单词中的每个字母打印了一行新的下划线。有没有办法摆脱这个?有人可以指导我的逻辑有什么问题吗?
word = "test"
def createBlank(word):
for letter in word:
blanks = '_' * len(word)
print(blanks)
我的结果如您所想:
>>> word
'test'
>>> createBlank(word)
____ #<- only need this line to be printed.. is it even possible using a for?
____
____
____
您正在为 word
中的字符数重复打印 blanks
。只需将 print(blanks)
移动到 for
循环之外:
word = "test"
def createBlank(word):
for letter in word:
blanks = '_' * len(word)
print(blanks)
演示:
>>> createBlank(word)
____
但是为什么需要 for
循环来打印下划线乘以 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,
这样它运行得更好
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)
我正在根据一组特定的说明使用 Python 编写刽子手游戏。我特别需要使用 for
循环来用下划线替换单词中的所有字母,事实上我已经成功地这样做了。但是我有一个小问题,我为单词中的每个字母打印了一行新的下划线。有没有办法摆脱这个?有人可以指导我的逻辑有什么问题吗?
word = "test"
def createBlank(word):
for letter in word:
blanks = '_' * len(word)
print(blanks)
我的结果如您所想:
>>> word
'test'
>>> createBlank(word)
____ #<- only need this line to be printed.. is it even possible using a for?
____
____
____
您正在为 word
中的字符数重复打印 blanks
。只需将 print(blanks)
移动到 for
循环之外:
word = "test"
def createBlank(word):
for letter in word:
blanks = '_' * len(word)
print(blanks)
演示:
>>> createBlank(word)
____
但是为什么需要 for
循环来打印下划线乘以 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,
这样它运行得更好
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)