5

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

Method 1

>>> 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

rɑːdʒɑ
  • 4,925
  • 13
  • 41
  • 77

6 Answers6

8

You can do it with:

print('.'.join(str(x) for x in deints))
Keiwan
  • 7,711
  • 5
  • 33
  • 48
4

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.

Community
  • 1
  • 1
ForceBru
  • 41,233
  • 10
  • 61
  • 89
4

You can use the join method on strings and have to convert the data in the list to strings first.

>>> '.'.join(map(str, deints))
'10.10.10.50'

join takes the string as a delimiter and concatenates the content of the list with this delimiter between each element.

Matthias
  • 11,699
  • 5
  • 39
  • 45
  • I'm not the down voter, but the problem here is that you need to `'.'.join` – ForceBru May 22 '16 at 17:34
  • Ah, right. But the abstraction should have been possible. It's funny, [first time I answered this kind of question](http://stackoverflow.com/questions/12053236/python-equivalent-for-phps-implode/12053276#12053276) I got positive reputation ... – Matthias May 22 '16 at 17:35
  • I need an integer not again in string. I have found what I need. Thank you – rɑːdʒɑ May 22 '16 at 17:44
  • @Raja: The list is unaltered. `map` applies the call to `str` to the list and gives back the changed result (an _iterable_ with strings) which is then used by `join`. – Matthias May 22 '16 at 17:46
2

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'
C14L
  • 11,487
  • 4
  • 34
  • 50
1

Just a non-join solution.

>>> print(*deints, sep='.')
10.10.10.50
Stefan Pochmann
  • 25,851
  • 7
  • 41
  • 100
0

Convert them into strings, then join them. Try using:

".".join([str(x) for x in x])
armatita
  • 11,531
  • 8
  • 49
  • 48