Search code examples
pythonpython-3.xloopsfor-loopiteration

Possibility to have no spaces when creating a string?


For example, if I do this:

for i in '12345':
        print("Welcome",i,"times")

It outputs:

Welcome 1 times
Welcome 2 times
Welcome 3 times
Welcome 4 times
Welcome 5 times

But I want it like this:

Welcome1times
Welcome2times
Welcome3times
Welcome4times
Welcome5times

Is this possible?


Solution

  • Yes you can, by using the sep parameter of the print function:

    for i in '12345':
        print("Welcome", i, "times", sep="")
    
    >>>
    Welcome1times
    Welcome2times
    Welcome3times
    Welcome4times
    Welcome5times
    

    By the way, you should think about generating your string using standard string formating methods. For example, you could do :

    for i in '12345':
        print("Welcome%stimes"%i)
    

    Or in a more python-3 way :

    for i in '12345':
        print("Welcome{i}times".format(i=i))
    

    Or even shorter (thanks @StefanPochmann)

    for i in '12345':
        print(f"Welcome{i}times")