0

i have a string with several "" in it, i need to replace a specific one. but this is not working, can anyone tell, me how to do this?

tried this

jsdump = jsdump.replace('"var"', card_var).strip()
jsdump = jsdump.replace("""var""", card_var).strip()

and nothing.

this is what i need:

card_var = cd1

basicly have: "in sentence","where "var" is ok"

need to replace to: "in sentence","where cd1 is ok"

2
  • 2
    The question is unclear. I suggest reformulating it including the current and wished behavior. For your problem try to use regex (import re) and create a dictionary with the words you want to replace: replacement_dict["var"]="cd1" Commented Sep 15, 2021 at 11:26
  • what dont you understand, maybe i can explain better, i need to replace a var in a string, the problem is that that var has "" so its dificult to build the replacement statement. Commented Sep 15, 2021 at 12:40

1 Answer 1

1

The solution I had in mind writing my comment:

import re
mystr = '"in sentence","where "var" is ok"'

replacement_dict = {"var": "cd1"}    # add other replacements to the dict following your needs
print(re.sub(r'"(\w+)"', lambda x: replacement_dict.get(x.group(1), x.group()) , mystr))

We replace the elements found in the dictionary (quotes are then removed) and let unchanged (quotes stay) if not in dictionary.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, will keep this for reference. in the meanwhile this jsdump = jsdump.replace('"var"', card_var).strip() started working fine :s

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.