我希望我的代码要做的是"-"
最终会与"0"
发生冲突。但是现在它所做的就是继续追逐"0"
并且永远不要碰它。
import time
global gunshot, gun
gun = 0
gunshot = "- 0"
while True:
global gunshot
gunshot = " " + gunshot
gunshot.replace(' 0', '0')
print ('\r {0}'.format(gunshot)),
if gunshot.find("-0") == 1:
gunshot = "-"
time.sleep(.1)
这就是我想要的:
- 0
- 0
- 0
这就是它正在做的事情
- 0
- 0
- 0
答案 0 :(得分:1)
replace返回一个新字符串,它不会改变该位置的变量。
gunshot = gunshot.replace(' 0', '0')
这将解决您的直接问题,但您应该考虑使用@MSeiferts代码,因为它要好得多。
答案 1 :(得分:1)
您可以在此处使用str.format
和str.rjust
功能:
bullet = '-'
target = 'O'
distance = 3
field = 10
while distance >= 0:
print('{}{}{}'.format(bullet, ' '*distance, target).rjust(field))
distance -= 1
打印:
- O
- O
- O
-O
答案 2 :(得分:0)
你也可以使用双端队列并只旋转值:
from collections import deque
def gunshot_path(distance):
return deque(['-'] + ([''] * (distance - 1)))
def print_gunshot_path(distance, target="0"):
path = gunshot_path(distance)
for i in range(distance):
print(" ".join(path) + target)
path.rotate()
print_gunshot_path(5)
print_gunshot_path(10, target='X')
打印哪些:
- 0
- 0
- 0
- 0
-0
- X
- X
- X
- X
- X
- X
- X
- X
- X
-X