Replace lines when specific characters are found in the Python string list

Asked 2 years ago, Updated 2 years ago, 18 views

I want to change the line whenever there is a letter 1 on the list.

The code I tried is as follows.

list_s = ["a","1","b","e","c","1","d","1","e"]


list_t = ["a","e"]

unit = ["1"]


cnt =0

for value in list_s:

    if value in list_t:
        del list_s[cnt]

    elif value in unit:
        list_s.insert(cnt-1',\n') #This part doesn't work;;
    cnt += 1

print(list_s)

python

2022-09-21 10:07

1 Answers

list_s = ["a","1","b","e","c","1","d","1","e"]
list_t = ["a","e"]
unit = ["1"]

temp = ""
cnt =0

for idx, value in enumerate(list_s):
    if value in list_t:
        temp += "\n"
    else:
        temp += value

print(temp)
#result

1b
c1d1

If you put \n in the list and print it out as a list,

['\n', '1', 'b', '\n', 'c', '1', 'd', '1', '\n']

It comes in a format.

To change the contents of the list other than the above method,

list_s = ["a","1","b","e","c","1","d","1","e"]
list_t = ["a","e"]
unit = ["1"]

temp = ""
cnt =0

for idx, value in enumerate(list_s):
    if value in list_t:
        list_s[idx] = "\n"
    else:
        list_s[idx] = value

print(''.join(list_s))
#result

1b
c1d1

You can also view the same execution results.


2022-09-21 10:07

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.