0

I have this code that contains multiple function. The output is fine except that the result of each function appears on a different line. I actually want the output concatenated as one item. I used +, %, f', almost everything I see on the net. Please help. The code is below.

import string
import asyncio

async def get_random_string(length):
    # choose from all lowercase letter
    letters = string.ascii_uppercase
    result_str = ''.join(random.choice(letters) for i in range(length))
    print(str(result_str))

    
async def my_function1():
  print(str(random.randint(0,9)))
  
async def my_function2():
  print(str(random.randint(100,999)))
  
async def my_function3():
  print(str(random.randint(100000,999999)))

if __name__ == "__main__":
   loop = asyncio.get_event_loop()
   loop.run_until_complete(asyncio.gather(my_function1(), get_random_string(3),\
   my_function2(), get_random_string(4), my_function3()))```

kaycia_g
  • 1
  • 1
  • Your functions shouldn't print their results, they should return them. Then you can combine them in any way you want. – Barmar Oct 21 '22 at 18:26
  • I see the close for duplicate related to new lines in `print` but in case the `asyncio`-ness was the point of confusion here, Does this answer your question? https://stackoverflow.com/questions/32456881/getting-values-from-functions-that-run-as-asyncio-tasks – ccchoy Oct 21 '22 at 18:37

1 Answers1

0

This is because print by default ends with a newline (\n) character.

You can override this:

def print_many_lines():
    print("line 1")
    print("line 2")
    print("line 3")

def print_one_line():
    print("line 1", end=" ")
    print("line 2", end=" ")
    print("line 3")

You could also change your code to have the functions return str instead and then just collect the resulting strings and print them all at once in one line like:

print(" ".join([func1(), func2(), func3()]))

(altho admittedly a little different for your example w/ asyncio - the idea is still the same)

For your asyncio case, your code just changes to:

# change all of the functions to `return str(...)` instead of `print(...)`

results = loop.run_until_complete(asyncio.gather(...)
print(" ".join(results))
ccchoy
  • 704
  • 7
  • 16
  • Thanks a million. You have no idea how much this helped me. – kaycia_g Oct 21 '22 at 18:43
  • Great! I'm curious if the reason for closing on this question was accurate - Does this [other post](https://stackoverflow.com/questions/493386/how-to-print-without-a-newline-or-space) answer your question? Does this [asyncio specific one](https://stackoverflow.com/questions/32456881/getting-values-from-functions-that-run-as-asyncio-tasks) answer your Q? If neither do, then maybe this question shouldn't have been closed and should instead be edited in some way and unclosed – ccchoy Oct 21 '22 at 19:12