w3resource

Python: Concatenate N strings

Python Basic: Exercise-81 with Solution

Write a Python program to concatenate N strings.

Pictorial Presentation:

Concatenate N strings

Sample Solution-1:

Python Code:

list_of_colors = ['Red', 'White', 'Black']  
colors = '-'.join(list_of_colors)
print()
print("All Colors: "+colors)
print()

Sample Output:

All Colors: Red-White-Black

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Sample Solution-2:

Concatenating With the + Operator:

Python Code:

Concatenating With the + Operator
print("Concatenating With the + Operator:")
list_of_colors = ['Red', 'White', 'Black'] 
colors = list_of_colors[0]+'-'+list_of_colors[1]+'-'+list_of_colors[2]
print("All Colors: "+colors)

Sample Output:

Concatenating With the + Operator:
All Colors: Red-White-Black

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Python Code Editor :

 

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to get the current value of the recursion limit.
Next: Write a Python program to calculate the sum of all items of a container (tuple, list, set, dictionary).

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Try-catch-else construct:

try:
  foo() 
except Exception: 
  print("Exception occured")
else:
  print("Exception didnt occur")
finally:
  print("Always gets here")