简体   繁体   中英

Adding different symbols inside a string using regular expression in Python

I am starting to learn Python but I have some struggles in using regular expression.

I need to perform the following task:

There is a variable MAX:

Max = "Max_Total:5 ,MAX_MAN:6 ,MAX_WOMEN:7 ,RELATION: In Relationship"

1) I need to to add double quotation marks in every w+_?w+.

For example: "Max_Total"

2) I need to add curly bracket at the beginning and the end of the string.

For example: {Max_Total:5 ,MAX_MAN:6 ,MAX_WOMEN:7 ,RELATION: In Relationship}

So I need to get the following outcome:

{"Max_Total":5 ,"MAX_MAN":6 ,"MAX_WOMEN":7 ,"RELATION": In Relationship}

I tried the follow codes and it works but I think my solution is bad. Can anyone teach me any alternative solution (preferably using RE)?

 Max = "Max_Total:5 ,MAX_MAN:6 ,MAX_WOMEN: 7,RELATION: In Relationship"

import re

Max1 =re.sub(r'^',"\"",Max)
Max2 =re.sub(r':',"\":",Max1)
Max3 =re.sub(r'^',"{",Max2)
Max4 =re.sub(r'$',"}",Max3)
Max5 =re.sub(r',',",\"",Max4)
print Max5

Thanks a lot!

I don't think that regular expressions are the best way in all of your modifications. However, you can use this

Max = "Max_Total:5 ,MAX_MAN:6 ,MAX_WOMEN: 7,RELATION: In Relationship"
Max = re.sub(r'^','{',Max)
Max = re.sub(r'$','}',Max)
# The following replaces Max_Total: for example with "Max_Total:"
Max = re.sub(r'([a-zA-Z_]+):', r'"\1":', Max)

I think that a better solution is:

Max = "Max_Total:5 ,MAX_MAN:6 ,MAX_WOMEN: 7,RELATION: In Relationship"
Max = re.sub(r'([a-zA-Z_]+):', r'"\1":', Max)
Max = '{' + Max + '}'
  • \\1 refers to group 1 , which is the one inside parentheses ( [a-zA-Z_]+ ).

  • [a-zA-Z_] matches any alphabetic character or underscore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM