V
V
Vasily Nikonov2020-11-05 17:59:31
Python
Vasily Nikonov, 2020-11-05 17:59:31

How to replace multiple elements in one line in Python?

There is an array in which some data is stored.

array = ["1-ая пара, предмет, аудитория", "2-ая пара, предмет, аудитория", 
         "2-ая пара, предмет, аудитория", "4-ая пара, предмет, аудитория"]

I need to replace some elements of a string with some other elements. What would it look like this:
array = ["9:40 - 10:30, предмет, аудитория", "10:40 - 12:10, предмет, аудитория",
         "12:50 - 14:20, предмет, аудитория", "14:30 - 16:00, предмет, аудитория"]

How can I do it more correctly without resorting to the construction:
for i in range(len(array):
    array[i] = array[i].replace("", "").replace("", "").replace("", ""). replace("", "")

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Summer Breeze, 2020-11-05
@jintaxi

schedule = {
    '1': '9:40 - 10:30',
    '2': '10:40 - 12:10',
    '3': '12:50 - 14:20',
    '4': '14:30 - 16:00'
}
array = [i.replace(f'{i[0]}-ая пара', schedule[i[0]]) for i in array]

V
Vlad Grigoriev, 2020-11-05
@Vaindante

The task is not complete, it is not clear what, when and how you plan to update.
the simplest is to use a regular expression,
a little more complicated but more visual to convert a string into a class, and replace the values ​​​​in it with a type like this

from dataclasses import dataclass


@dataclass
class Record:
    times: str = None
    name: str = None
    room: str = None


array = ["1-ая пара, предмет, аудитория", "2-ая пара, предмет, аудитория",
         "2-ая пара, предмет, аудитория", "4-ая пара, предмет, аудитория"]

schedule = [Record(*v.split(',')) for v in array]
new_parsing_times = ["9:40 - 10:30", "10:40 - 12:10", "12:50 - 14:20", "14:30 - 16:00"]
for record, new_times in zip(schedule, new_parsing_times):
    record.times = new_times

print(schedule)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question