I'm using an API that returns § characters with a color code (1-9 or a-h) which I want to eliminate (§ and following character). Their purpose is for color formatting but I'm not using that and my method iterates through a string to remove them but could not find a better way and it fees too hacky and buggy. Is there like a parameter for the str.replace function that removes the letter after the found character?
            Asked
            
        
        
            Active
            
        
            Viewed 86 times
        
    0
            
            
        
        WindowsIsCool
        
- 25
 - 1
 - 7
 
- 
                    1Replace all the characters that are not alphanumeric. [How to input a regex in string.replace?](https://stackoverflow.com/questions/5658369/how-to-input-a-regex-in-string-replace) – Yoshikage Kira Jun 12 '21 at 01:20
 
1 Answers
0
            You can "eliminate" the precise pattern with regular expressions using the sub method:
import re
def clean_string(s):
    return re.sub(r"\$[1-9a-h]", "", s)
clean_string("foo $4 - bar $f")
# > 'foo  - bar '
If you want more flexibility, you can match any non whitespace character following $ with \S:
import re
def clean_string(s):
    return re.sub(r"\$\S", "", s)
        Whole Brain
        
- 2,097
 - 2
 - 8
 - 18
 
- 
                    is there any way i could use like * or something to represent any character for more flexibility? – WindowsIsCool Jun 12 '21 at 02:32
 - 
                    Yes you can. I updated the answer. If it's too broad (because it also catches symbols after the `$`), you can specify any character you want between brackets, like `r"\$[\wéàÉü]"`. – Whole Brain Jun 12 '21 at 02:40