Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 681
Arik gorun Avatar asked Feb 26 '18 19:02

Arik gorun


People also ask

How do you replace all characters in a string?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag.

How do you replace all values in a string?

replaceAll() The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match. The original string is left unchanged.

How do you replace all characters in a string in Python?

Python String | replace() replace() is an inbuilt function in the Python programming language that returns a copy of the string where all occurrences of a substring are replaced with another substring. Parameters : old – old substring you want to replace. new – new substring which would replace the old substring.


2 Answers

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))
like image 116
mypetlion Avatar answered Oct 24 '22 14:10

mypetlion


import re

str = "abcdefghi"
print(re.sub('[a-z]','_',str))
like image 24
jonhid Avatar answered Oct 24 '22 13:10

jonhid