-1

Let's say I have a string like this:

content ='''38%
46%
54%
62% 
70% 
78% 
86%'''

I want to wrap quotation marks around the values in each line. My attempt to do so is like so:

formatted_answers = re.sub("([^\s]+)", "'\1'", content)
print(formatted_answers)

But this returns

''
''
''
'' 
'' 
'' 
''

Can't see what I'm doing wrong

Parseltongue
  • 11,157
  • 30
  • 95
  • 160
  • This string `"'\1'"` is parsed by the language as `'` plus the octal character `001` plus another `'` So you are substituting a quoted control-1 character. Double escape the escape like this `"'\\1'"` and it will feed the quoted backreference `'\1'` as the replacefment. –  Jul 22 '20 at 21:43
  • Likewise, `"([^\s]+)"` is being parsed as `([^s]+)` but it works because you don't have any `s` in the source you show. So obviously `"(.*)"` is better since it matches horizontally any character. –  Jul 22 '20 at 21:46
  • Thats odd @WiktorStribiżew you've marked this as a duplicate of `Python re.sub back reference not back referencing [duplicate]` which is also markedd as a duplicate. Why a duplicate of a duplicate ? –  Jul 22 '20 at 21:50

1 Answers1

0

Put raw string (r) as second parameter in re.sub():

content ='''38%
46%
54%
62%
70%
78%
86%'''

formatted_answers = re.sub("([^\s]+)", r"'\1'", content)  # <-- r here!
print(formatted_answers)

Prints:

'38%'
'46%'
'54%'
'62%'
'70%'
'78%'
'86%'
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • Unfortunately, if there are spaces anywhere in the content, it will wrap quotes around every object with spaces. `'$796' 'a' 'week'` Do you know how to wrap quotes only around the first and end of each line? – Parseltongue Jul 22 '20 at 21:22
  • 1
    Nevermind, I just replaced the match with: `(.*)` – Parseltongue Jul 22 '20 at 21:24