3

Suppose I have a string

the_string = "the brown fox"

And I wan't to replace the spaces with a number of characters, for example, 5 dash marks

new_string = "the-----brown-----fox"

but this will be a variable, so i cant just do:

the_string = 'the brown fox'
new_string = re.sub(r'\s', '-----', the_string)

I need something like the following:

the_string = 'the brown fox'
num_dashes = 5
new_string = re.sub(r'\s', r'-{num_dashes}', the_string)

Is something like this possible?

3
  • Is there some reason you do not want to use str.replace(old, new[, count])? You could write new_string = the_string.replace(' ', '-' * num_dashes). Commented Aug 18, 2015 at 20:35
  • In this case that would work just fine. Does str.replace work with a regex? For example if I need to replace one or more spaces. Could be one, could be multiple. Commented Aug 19, 2015 at 5:58
  • Then you are correct. You would want to use the re module for a variable number of whitespace characters. The str.replace method does not work with regular expressions. Commented Aug 19, 2015 at 13:02

2 Answers 2

3

Yes, you can do this:

the_string = 'the brown fox'
num_dashes = 5
re.sub(r'\s', '-'*num_dashes, the_string)
Sign up to request clarification or add additional context in comments.

Comments

2
def repl(matchobj):
    if matchobj.group():
        #do something
        #return whatever you want to replace

my_str = "the brown fox"

pattern = r"\s+"
print re.sub(pattern, repl, my_str)

You can define a function in re.sub

1 Comment

That's genius, THANKS A LOT

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.