Replace all alpha characters within double quotes with underscores? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Replace all alpha characters within double quotes with underscores? (/thread-6501.html) |
Replace all alpha characters within double quotes with underscores? - walterbyrd - Nov-25-2017 For example, I want to change this string: Quote:'abc "this that" xyz' with this string: Quote:'abc ____ ____ xyz' There will only be one pair of double quotes in the string. I think I know how to find the positions of the double quote delimiters, and how to replace an alpha character with an underscore. But I am not about how to put it into a loop. import re s = 'abc "this that" xyz' d = '"' # find and print order of " delimiter print ( [pos for pos, char in enumerate(s) if char == d] ) # replace t = s.replace(s[i], '_') RE: Replace all alpha characters within double quotes with underscores? - Larz60+ - Nov-26-2017 If you play with it, you can make this more compact. I'd do it myself, but getting tired. import re s = 'abc "this that" xyz' i1, i2 = [match.start() for match in re.finditer('"', s)] s1 = s[:i1] for char in s[i1+1:]: if char == '"': break if char != ' ': s1 += '_' else: s1 += ' ' s1 += s[i2+1:] print(s1)prints:
|