Reputation: 6633
Right now I am having a list
>>> deints
[10, 10, 10, 50]
I want to print it as 10.10.10.50
. I made it as
>>> print(str(deints[0])+'.'+str(deints[1])+'.'+str(deints[2])+'.'+str(deints[3]))
10.10.10.50
Are there any other ways we can acheivie this ?
Thank you
Upvotes: 10
Views: 68051
Reputation: 51
Convert them into strings, then join them. Try using:
".".join([str(x) for x in x])
Upvotes: 0
Reputation: 28606
Just a non-join
solution.
>>> print(*deints, sep='.')
10.10.10.50
Upvotes: 1
Reputation: 12558
Obviously str.join()
is the shortest way
'.'.join(map(str, deints))
or if you dislike map()
use a list comprehension
'.'.join([str(x) for x in deints])
you could also do it manually, using *
to convert the deints
list into a series of function arguments
'{}.{}.{}.{}'.format(*deints)
or use functools.reduce
and a lambda
function
reduce(lambda y, z: '{}.{}'.format(y, z), x)
All return
'10.10.10.50'
Upvotes: 2
Reputation: 44838
This is very simple. Take a look at str.join
print '.'.join([str(a) for a in deints])
Citation from the docs:
str.join(iterable)
Return a string which is the concatenation of the strings in the iterable iterable. The separator between elements is the string providing this method.
Upvotes: 6