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
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:
- Create a String of N Characters in Python
- How to Create a String with Newline in Python
- Create a String from a List with a Separator in Python
- How to Convert a Dictionary to a String in Python?
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.