Python Forum
Replace all alpha characters within double quotes with underscores?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Replace all alpha characters within double quotes with underscores?
#1


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], '_')
Reply
#2
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:
Output:
abc ____ ____ xyz
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  alpha advantage api question jacksfrustration 1 449 Oct-09-2023, 03:39 PM
Last Post: Larz60+
  TypeError: max_value() missing 2 required positional arguments: 'alpha' and 'beta' Anldra12 2 4,169 May-15-2021, 04:15 PM
Last Post: Anldra12
  Remove single and double quotes from a csv file in 3 to 4 column shantanu97 0 6,930 Mar-31-2021, 10:52 AM
Last Post: shantanu97
  Two types of single quotes Led_Zeppelin 2 1,863 Mar-15-2021, 07:55 PM
Last Post: BashBedlam
  Remove double quotes from the list ? PythonDev 22 8,559 Nov-05-2020, 04:53 PM
Last Post: snippsat
  Quotes vs. no quotes around numbers Mark17 6 3,073 Aug-06-2020, 04:13 AM
Last Post: t4keheart
  Remove escape characters / Unicode characters from string DreamingInsanity 5 13,429 May-15-2020, 01:37 PM
Last Post: snippsat
  Python 3.9 alpha how to install psutil? lmh1 10 8,678 Apr-12-2020, 11:25 AM
Last Post: lmh1
  Alpha numeric element list search rhubarbpieguy 1 1,746 Apr-01-2020, 12:41 PM
Last Post: pyzyx3qwerty
  Cannot Remove the Double Quotes on a Certain Word (String) Python BeautifulSoup soothsayerpg 5 6,994 Oct-27-2019, 09:53 AM
Last Post: newbieAuggie2019

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020