0

I have a string like this '[[20, 20.4,aa], [c, 10.5, eee]]'. My aim is to enclose the characters inside single quotes and leave the numbers as it is.

For example:

examples:
s1 = "[[20, 20.4, aa], [c, 10.5, eee]]"
s2 = "[[a , bg, 20], [cff, 20, edd]]"

required:
s1 = "[[20, 20.4,'aa'], ['c', 10.5, 'eee']]"
s2 = "[[a , 'bg', 20], ['cff', 20, 'edd']]"

I have done so far this:

s = '[[20, 20.4,a], [c, 10.5, e]]'

s = ''.join(["'"+ i + "'" if i.isalpha() else i for i in s])
s # "[[20, 20.4,'a'], ['c', 10.5, 'e']]"

But it works only for single characters. If I have aa it will give 'a''a' which is wrong. How the problem can be fixed?

1 Answer 1

2

You could use sub:

import re

s1 = '[[20, 20.4,aa], [c, 10.5, eee]]'
s2 = '[[a , bg,20], [cff, 20, edd]]'

rs1 = re.sub('([a-zA-Z]+)', r"'\1'", s1)
print(rs1)
rs2 = re.sub('([a-zA-Z]+)', r"'\1'", s2)
print(rs2)

Output

[[20, 20.4,'aa'], ['c', 10.5, 'eee']]
[['a' , 'bg',20], ['cff', 20, 'edd']]

The pattern ([a-zA-Z]+) means match one or more letters and put them inside a group, then refer to that group r"'\1'" and surrounded with single quotes.

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

1 Comment

follow up: how to do the same for s = '10.5 [c, 10.5, eee]]' to get mylist = [10.5, ['c', 10.5, 'eee']] ?

Your Answer

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