1

What I want my code to do is that eventually the "-" will collide with the "0". But right now all it does is keep chasing the "0" and never touch it.

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)

That is want I want:

     -     0
      -    0
       -   0

This is what it is doing

     -     0
     -     0
     -     0
3
  • 2
    You are replacing the space but not assigning the result into gunshot. Gunshot = gunshot.replace() Commented Jan 31, 2017 at 3:08
  • oh thanks i just noticed Commented Jan 31, 2017 at 3:13
  • You don't need to declare global variables like that: global gunshot, gun. That makes only sense if you are in a function and want to modify a gunshot and gun variable (which are outside of your function). Commented Jan 31, 2017 at 3:23

3 Answers 3

1

replace returns a new string, it does not change the variable inplace.

gunshot = gunshot.replace(' 0', '0')

This will fix your immediate problem, but you should consider using @MSeiferts code because it is much better.

Sign up to request clarification or add additional context in comments.

2 Comments

how do i change variable inplace?
You can't change a string in-place in Python but you can reassign the variable name.
1

You could use the str.format and str.rjust function here:

bullet = '-'
target = 'O'

distance = 3
field = 10

while distance >= 0:
    print('{}{}{}'.format(bullet, ' '*distance, target).rjust(field))
    distance -= 1

which prints:

     -   O
      -  O
       - O
        -O

Comments

0

You could also use a deque and just rotate the values:

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')

Which prints:

-    0
 -   0
  -  0
   - 0
    -0
-         X
 -        X
  -       X
   -      X
    -     X
     -    X
      -   X
       -  X
        - X
         -X

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.