Select to view content in your preferred language

Function

1943
11
Jump to solution
03-16-2021 07:49 PM
Mick
by
Emerging Contributor
 
0 Kudos
1 Solution

Accepted Solutions
by Anonymous User
Not applicable

I don't know why that would make it un-pythonic since it is readable, simple, practical, and easy to implement/ explain without the assistance of code comments or knowledge of regex symbols/ functionalities. I say easier because we code for people, not machines and it may 'look' bad with the chaining, but it is easily understood by people at all skill levels vs trying to decipher regex expressions. ...A newbie might think that you are replacing [!+]. in the string at first glance and try to 'fix' it without looking at what the expression is doing.

To answer the 'what if I wanted to' question, (couldn't tell if you meant they are together or is a third character) add another replace. If you feel there are too many replaces being chained in your code, just add the character to a list and iterate over them:

charReplace = ['+', '!', '.', 'some']

inString = 'awesome this+ is a. Message!'

for chr in charReplace:
    if chr in inString:
        inString = inString.replace(chr, '-')

I do think that regex has a place and that was a nice, succinct re.sub example you provided and if it works, that is great- I personally think that regex can introduce complexity and over-complicate code so I use it sparingly when other methods would become too complex/complicated.

View solution in original post

11 Replies
by Anonymous User
Not applicable
Easiest way is probably just to chain it.

foo = my.read().replace(‘+’, ‘-‘).replace(‘!’, ‘-‘)

try is a reserved word (part of try-except) so I’d suggest you change it to a different name.
DanPatterson
MVP Esteemed Contributor

leaving out regular expressions or the string "translate" options

Code Golf

 

x = '+-!#'
y = "ab+!#-cd"
[i if i not in x else "-" for i in y ]
['a', 'b', '-', '-', '-', '-', 'c', 'd']

def goodbad(y, x):
    if y not in x:
        return i
    return "-"
    
for i in y:
    print(goodbad(i, x))
a
b
-
-
-
-
c
d

Or this

def goodbad(y, x):
    return "".join(["-" if i in x else i for i in y  ])
    
goodbad(y, x)
'ab----cd'

 


... sort of retired...
curtvprice
MVP Esteemed Contributor

I am tempted by @Anonymous User  but what if I want to replace three characters? Too many .replace()'s and it starts to get darn un-Pythonic.

I don't know why @DanPatterson did not go there with reg expressions. They are just so beautiful...

 

>>> import re
>>> text = foo!+bar'
>>> re.sub('[!+]', '-', text)
'foo--bar'
>>> re.sub('[!+].', '-', text)
'foo-bar'

 

DanPatterson
MVP Esteemed Contributor

because 're' only works with text... 'in' can be used with other object types 😉


... sort of retired...
0 Kudos
BlakeTerhune
MVP Regular Contributor

As much as regex is still black magic to me, it does seem like the best solution here.

0 Kudos
by Anonymous User
Not applicable

I don't know why that would make it un-pythonic since it is readable, simple, practical, and easy to implement/ explain without the assistance of code comments or knowledge of regex symbols/ functionalities. I say easier because we code for people, not machines and it may 'look' bad with the chaining, but it is easily understood by people at all skill levels vs trying to decipher regex expressions. ...A newbie might think that you are replacing [!+]. in the string at first glance and try to 'fix' it without looking at what the expression is doing.

To answer the 'what if I wanted to' question, (couldn't tell if you meant they are together or is a third character) add another replace. If you feel there are too many replaces being chained in your code, just add the character to a list and iterate over them:

charReplace = ['+', '!', '.', 'some']

inString = 'awesome this+ is a. Message!'

for chr in charReplace:
    if chr in inString:
        inString = inString.replace(chr, '-')

I do think that regex has a place and that was a nice, succinct re.sub example you provided and if it works, that is great- I personally think that regex can introduce complexity and over-complicate code so I use it sparingly when other methods would become too complex/complicated.

JoshuaBixby
MVP Esteemed Contributor

There is a very long discussion on this topic with lots of suggestions over @ python - How to replace multiple substrings of a string? - Stack Overflow

DanPatterson
MVP Esteemed Contributor

We all await the 'walrus'... python 3.8, where are you!

# text = "The quick brown fox jumps over the lazy dog"
# replacements = [("brown", "red"), ("lazy", "quick")]
[text := text.replace(a, b) for a, b in replacements]
# text = 'The quick red fox jumps over the quick dog'

 (Xavier Guidot in Joshua's link ) 


... sort of retired...
BlakeTerhune
MVP Regular Contributor

I had to learn more about this walrus you speak of.

"There is new syntax := that assigns values to variables as part of a larger expression. It is affectionately known as “the walrus operator” due to its resemblance to the eyes and tusks of a walrus."

0 Kudos