0

Just wondering how I would not have the replace method applied to a specific item in a list (but to the rest). In this example, how I would not apply it to the 3rd item (the 'c' string)?

ls_c = ['a', 'b', 'c', 'd', 'e', 'f']
ls_c_a = (','.join(ls_c))
ls_c_a_1 = ls_c_a.replace(',', '\n')
print('test' + ls_c_a_1)

So the output would look like:

testa
bc
d
e
f

Thanks in advance.

2 Answers2

1

Supposing that the 3rd item will always be "c" string, you could try this:

ls_c_a_1 = ''.join([item if "b" in item else item + "\n" for item in ls_c_a.split(",")])

If this value can be changed, use this:

ls_c_a_1 = [item + "\n" for item in ls_c_a.split(",")]
ls_c_a_2 = ''.join([a[i].replace("\n", "") if i == 1 else a[i] for i in range(len(a))])
  • Using your output as metric, because if you want to keep the "," between "b" and "c", just change the replace to replace("\n", ",") – Felipe Vila Chã Apr 22 '21 at 14:58
0

You can use a regular expression to find all instances of commas where a c doesn't succeed the comma, using a negative lookahead (?!):

,(?![c])

Then, you can use the Pattern.sub() method to substitute all discovered commas with a newline.

>>> import re
>>> string = ",".join(ls_c)
>>> regex = re.compile(r",(?![c])")
>>> print(regex.sub("\n", string))
a
b,c
d
e
f
Jacob Lee
  • 4,405
  • 2
  • 16
  • 37