0

I have a section of code which looks like this:

for l in blah: sys.stdout.write(l) sys.stdout.flush() time.sleep(0.025)

which adds a slight delay between each character being printed in a print statement, which is assigned to the variable blah. However, if there is a variable present in the print statement, so for instance:

blah = "\n", player_name, ", you must save this land from the virus that has blighted us.\n"

then the print statement will not print as I wanted it to, but rather as a normal print statement would.

I expected the print statement to be printed as if it were being typed quickly, line by line, but instead, the print statement was printed all at once.

  • `"\n", player_name, ", you must save this land from the virus that has blighted us.\n"` is a _tuple_ of three elements, two of which are strings. So, `blah[2]` is the string `", you must save this land from the virus that has blighted us.\n"`. – ForceBru Oct 14 '19 at 18:26
  • `blah` as you show is a tuple not a string. You could convert it to string with something like what's mentioned in https://stackoverflow.com/questions/19641579/python-convert-tuple-to-string – luis.parravicini Oct 14 '19 at 18:27

1 Answers1

0

You can use an "f-string":

blah = f"\n{player_name}, you must save this land from the virus that has blighted us.\n"

This allows you to substitute variables that are currently in scope (e.g. player_name) directly into the string you're building. If player_name was 'Alex', then the resulting blah would be "\nAlex, you must..."


What you were doing was assigning a tuple to blah. When you then tried to iterate over it, you got "each element of the tuple", rather than "each character of the string". The built-in print() function lets you give an arbitrary number of arguments, and internally that does resolve itself as a tuple, but most functions don't let you do that.

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53