Replace strings that starts with a char and ends with space

Question:

I need to put quotation marks around words that begin with an @ and end with a space:

For example, consider the following string:

mystring = "@id string,@type string,account struct<@id string,@type string,accountId:string>"

The expected output will be:

mystring_expected = "`@id` string,`@type` string,account struct<`@id` string,`@type` string,accountId:string>"

How can I do it in Python?

Asked By: Eric Bellet

||

Answers:

Just use a regex to match @ and one or more word characters, then wrap that with `

import re

mystring = "@id string,@type string,account struct<@id string,@type string,accountId:string>"
new_mystring = re.sub(r"(@w+)", r"`1`", mystring)


mystring_expected = "`@id` string,`@type` string,account struct<`@id` string,`@type` string,accountId:string>"
print(new_mystring == mystring_expected)
Answered By: Samathingamajig

you could use a regular expression to find the words and put quotes using the re.sub function:

import re

mystring = "@id string,@type string,account struct<@id string,@type string,accountId:string>"

pattern = r"(@w+b)"
mystring_expected = re.sub(pattern, r"`1`", mystring)
print(mystring_expected)
Answered By: Roniel López
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.