Replace lines when certain characters are found in the Python list

Asked 2 years ago, Updated 2 years ago, 16 views

Whenever I find "1" in the list_s, I want to change the line in front of it without deleting it.

In the current code, "1" is deleted and changed.

list_t is the list to be deleted. The unit is a list containing the letter "1".

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 unit:
        temp += "\n"
    elif value in list_t:
        pass
    else:
        temp += value


print(''.join(temp))

Expected results are

1bc
1d
1

This is.

python

2022-09-21 10:06

1 Answers

temp = ""

for value in list_s:
    if value in unit:
        temp += "\n" + str(value)
    elif value in list_t:
        pass
    else:
        temp += value

print(temp)


2022-09-21 10:06

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.