Arik gorun
Arik gorun

Reputation: 73

How to replace ALL characters in a string with one character

Does anyone know a method that allows you to replace all the characters in a word with a single character?

If not, can anyone suggest a way to basically print _ (underscore) the number of times which is the length of the string itself without using any loops or ifs in the code?

Upvotes: 7

Views: 16681

Answers (2)

jonhid
jonhid

Reputation: 2135

import re

str = "abcdefghi"
print(re.sub('[a-z]','_',str))

Upvotes: 5

mypetlion
mypetlion

Reputation: 2524

mystring = '_'*len(mystring)

Of course, I'm guessing at the name of your string variable and the character that you want to use.

Or, if you just want to print it out, you can:

print('_'*len(mystring))

Upvotes: 18

Related Questions