Home > Software engineering >  Python Print List in a Sentence (Dynamic List)
Python Print List in a Sentence (Dynamic List)

Time:04-26

I'm stuck in a section of my code that I need to manipulate. This list isn't always going to have a length of 4. Sometimes it could be 1, 10, or 20; just depends.

mylist = ['1.1.1.1', '2.2.2.2', '3.3.3.3', '4.4.4.4']
length = len(mylist)
print(f'Here are the addresses: "mylist[1]" "mylist[2]" "mylist[3]" "mylist[4]"')

Need the output to look like this:

Here are the addresses: "1.1.1.1" "2.2.2.2" "3.3.3.3" "4.4.4.4"

I'm not sure how to put that in a for loop

CodePudding user response:

You can just join it with str.join and then print. For eg.

mylist = ['1.1.1.1', '2.2.2.2', '3.3.3.3', '4.4.4.4']
print_list = " ".join([f'"{addr}"' for addr in mylist])
print(f"Here are the addresses: {print_list}")

This will not consider how many elements are going to be there, it merges everything and prints.

CodePudding user response:

You can try this

mylist = ['1.1.1.1', '2.2.2.2', '3.3.3.3', '4.4.4.4']
length = len(mylist)
print('Here are the addresses: "{0}" "{1}" "{2}" "{3}"'.format(*mylist))
  • Related