Python String - Append in Loop


Python String - Append in Loop

To append values in an iterable to a string in Python, you can use various techniques depending on the specific requirements. For example, you can use a For loop and string concatenation, or While loop with string concatenation.

In this tutorial, we shall go through these two approaches, and learn how to append values to a string in a loop with examples.

1. Append values in loop to a string using For loop in Python

Given an iterable with values in x. We have to append the values in x to a string using For loop.

Steps

  1. Take values (which is an iterable) in a variable x.
x = ["Apple", "Banana", "Cherry"]
  1. Take a variable result with empty string to store the resulting string.
result = ""
  1. Use Python For loop to iterate over each value in the values iterable x, convert each value to string using str() built-in function, and append the converted value to the resulting string result using string concatenation operator +.
for value in x:
    result += str(value)
  1. After the For loop is done, result has all the values in x appended to the string in result. You may use it as per your requirement. In this program, we shall print it to console output.

Program

The complete program to append values in a loop to a string using For loop.

Python Program

# Values
x = ["Apple", "Banana", "Cherry"]

# Take a variable with empty string to store result
result = ""

# For loop to append values to a string
for value in x:
    result += str(value)

print(result)

Output

AppleBananaCherry

Now, let us take some different type of values like integer, float, etc., in the values list and run the program again.

Python Program

# Values
x = ["Apple", 3.14, "Fig", 452]

# Take a variable with empty string to store result
result = ""

# For loop to append values to a string
for value in x:
    result += str(value)

print(result)

Output

Apple3.14Fig452

2. Append values in loop to a string using While loop in Python

Given an iterable with values in x. We have to append the values in x to a string using While loop.

Steps

The steps are same as that of in the previous example, except that we use a Python While loop to iterate over the values.

Program

The complete program to append values in a loop to a string using While loop.

Python Program

# Values
x = ["Apple", "Banana", "Cherry"]

# Take a variable with empty string to store result
result = ""

# While loop to append values to a string
i = 0
while i < len(x):
    result += str(x[i])
    i += 1

print(result)

Output

AppleBananaCherry

Summary

In this Python Strings tutorial, we learned how to append values in a loop to a string. In the first approach, we used For loop with string concatenation operator. In the second approach, we used While loop with string concatenation operator. We have covered programs for each of these approaches and learned how to append values in a loop to a string in Python.