Replace all characters in string with asterisks – Python

In this article, we will discuss different ways to replace all characters in a string with asterisks i.e. “*”.

Table Of Contents

Suppose we have a string like this,

"Testing"

After replacing all characters in this string with asterisks, the final string should be like,

"*******"

Number of asterisks in the final string should be same as the number of characters in the original string. There are different ways to do this. Let’s discuss them one by one.

Using len() function

As we need to replace all the characters in a string with an asterisk ‘*’ symbol. So, we can just count the number of characters in the string and create a new string what that many asterisks. Then assign this new string to the original variable. It will give an effect that we have replaced all the characters in the string with asterisks.

For example,

strValue = "Testing"

# Replace all characters in a string with asterisks
strValue = '*' * len(strValue)

print(strValue)

Output:

*******

It replaced all the characters in the string with asterisks i.e. ‘*’.

By converting into list

As strings are immutable in Python. Therefore, we can not modify its contents using [] operator. But we can convert a string to list and then change its contents using the subscript operator ([]). Now to replace all characters in string with asterisks, we can use the this technique i.e.

  • Convert the string to list.
  • Iterate over list and replace each value with ‘*’ using subscript operator.
  • Join all characters in list and create a string again.
  • This string will contain only asterisks.
  • Assign this string back to the original variable.

It will give an effect that we have replaced all the characters in string with asterisks.

For example,

strValue = "Testing"

# Convert string to list
listOfChars = list(strValue)

# Iterate over all characters in list
# and replace them with asterisks.
for i in range(len(strValue)):
    listOfChars[i] = '*'

# Convert list to string, containing all asterisks 
strValue = ''.join(listOfChars)

print(strValue)

Output:

*******

It replaced all the characters in the string with asterisks i.e. ‘*’.

Summary:

We learned about different ways to replace all the characters in a string with asterisks in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top