johnn trann
johnn trann

Reputation: 19

Removing specific set of characters?

I know a code like this

translated1 = str(''.join( c for c in translated2 if c not in "[']" ))

will remove any instances of [ or ' or ] but how would I code it so that it removes "---" exactly this.

I don't want it to remove any instances of "-", only if those 3 are together at once.

How can I do that? Thank you!

Upvotes: 0

Views: 43

Answers (2)

shaeed
shaeed

Reputation: 453

This can be done very easily by regular expression. You can read more about python regular expression here.

You can use it like this-

import re
str1 = 'there is three --- and now single - and now two --'
str2 = re.sub('---', '', str1)
print(str2)

Output-

there is three  and now single - and now two --

DEMO

Upvotes: 1

Marc Cataford
Marc Cataford

Reputation: 1

You can use str.replace(patt, repl):

s = "---test--test-test----"
print(s.replace("---", ""))
# "test--test-test-"

You could also do it using re if you want something more extensible.

Upvotes: 0

Related Questions