Python - Create String of specific Length


Python - Create String of specific Length

To create a string of specific length in Python, you can take a character and repeat it in the string using string repetition, or string concatenation in a loop.

In this tutorial, you will learn how to create a string of specific length in Python using string repetition, or string concatenation in a loop, with examples.

Examples

1. Create string of specific length using string repetition in Python

You can use multiplication operator * with the required char to repeat as left operand, and the required length of string as right operand. The operator returns a string of specified length with the character repeated through out the string.

The complete Python program to create a string of specific length using multiplication operator is given below.

Python Program

# Given character
char = "x"

# Required string length
string_length = 10

# Create string of specified length
result_string = char * string_length

print(f"Result string : {result_string}")

Output

Result string : xxxxxxxxxx

Related Tutorials

2. Create string of specific length using For loop in Python

You can also use a For loop to concatenate a given character for N times to create a string of length N.

The complete Python program to create a string of specific length using For loop is given below.

Python Program

# Given character
char = "a"

# Required string length
string_length = 10

# Create string of specified length
result_string = ""
for _ in range(string_length):
    result_string += char

print(f"Result string : {result_string}")

Output

Result string : aaaaaaaaaa

Related Tutorials

Summary

In this tutorial, we learned how to create a string of specific length using string repetition, or string concatenation in a loop, with the help of examples.