How to Create a String of Same Character in Python

In this Python programming tutorial, we’ll learn how to create a string of the same character in Python. This can be useful in various situations, such as formatting text or creating a visual representation of data.

Create a String of Same Character in Python

We will see here two methods for creating a string of same character in Python.

1. Using the * operator

The simplest way to create a string of the same character in Python is by using the * operator. This operator can be used to repeat a string a specified number of times.

char = '-'
length = 10
string = char * length
print(string)

Output:

----------

Here is another example;

city_names = ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix']
separator = '-' * 20

for city in city_names:
    print(separator)
    print(city)

Output:

--------------------
New York
--------------------
Los Angeles
--------------------
Chicago
--------------------
Houston
--------------------
Phoenix
Create a String of Same Character in Python
Create a String of Same Character in Python

2. Using the str.join() method

Another way to create a string of the same character is by using the str.join() method in Python. This method concatenates a list of strings, using the specified character as a separator.

Example:

char = '-'
length = 10
string = char.join([''] * (length + 1))
print(string)

Output:

----------

Example-2:

Here is another example.

city_names = ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix']
separator = '-'.join([''] * 21)

for city in city_names:
    print(separator)
    print(city)

Output:

--------------------
New York
--------------------
Los Angeles
--------------------
Chicago
--------------------
Houston
--------------------
Phoenix

Conclusion

In this Python tutorial, we’ve learned how to create a string of the same character in Python using two different methods: the * operator and the str.join() method.

You may also like: