0

Following is my code. I want to append the ip:port string by a comma separated list.

ip = ['1.1.1.1', '2.2.2.2', '3.3.3.3', '4.4.4.4']
memcache = ''
port = '11211'
for node in ip:
    memcache += str(node) + ':' + port
    # join this by comma but exclude last one

I want output in this format:

memcache = 1.1.1.1:11211, 2.2.2.2:11211, 3.3.3.3:11211, 4.4.4.4:11211

How can I achieve that?

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
Capricorn
  • 701
  • 1
  • 10
  • 20
  • possible duplicate of [Concatenate elements of a list](http://stackoverflow.com/questions/16522362/concatenate-elements-of-a-list) – Felix Kling Jan 30 '14 at 10:09

3 Answers3

5

memcache = ', '.join("{0}:{1}".format(ip_addr, port) for ip_addr in ip)

Ewan
  • 14,592
  • 6
  • 48
  • 62
4
memcache = ', '.join(address + ':' + port for address in ip)

This uses the join method to join strings with ', ' as a separator. A generator expression is used to append the port to each address; this could also be done with a list comprehension. (There's actually no performance benefit to the genexp in this context, but I prefer the syntax anyway.)

user2357112
  • 260,549
  • 28
  • 431
  • 505
1
memcache = ', '.join(address + ":" + port for address in ip)

best Peter

Peter
  • 103
  • 1
  • 8