简体   繁体   中英

sys.stdout.write() and .flush() with variables

I've been working on an RPG game and I like how the sys.stdout.write() and .flush() give it the effect of typing out the letters. But when I put a variable into to the sentence I want to type out, it doesn't type out any bit of the sentence, not even the parts I have in quotes (non variables). I was wondering if there was a way around this that didn't include me writing seperate code blocks for the variables and what's in quotes, and maybe make it type out the variable.

if girl1 == True:
   t="You and",girl1realname,"have found a sandy beach while looking for a 
   place of shelter. \nWhether you look left or right, the beach ranges for 
   miles.\n"
   y=girl1realname+": 'Hey, I guess I always wanted a house on the beach...I 
   think. I can't really remember.'\n"
   for char in (t):
       time.sleep(0.05)
       sys.stdout.write(char)
       sys.stdout.flush()
   time.sleep(1)
   for char in (y):
       time.sleep(0.05)
       sys.stdout.write(char)
       sys.stdout.flush()

In your definition of t , the commas will make it a tuple. Iterating that should then write each chunk ( "You and" , girl1realname , and "have found..." ) at a time instead of each char in each chunk. Replace the commas with + .

Your definition of y appears to be fine.

As for reusing, you can define a function like:

def typeout(x):
  for char in x:
    time.sleep(0.05)
    sys.stdout.write(char)
    sys.stdout.flush()

Used like:

typeout(t)
time.sleep(1)
typeout(y)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM