How to serialize data and fix the wrong one in Python?

Question:

I’m new to Python. I need to serialize the data by the first two chars is taken from the first and the last char in the given string plus the transposed number just like this one:

Input: ["HOMAGE", "DESIGN", "PROTECTION", "COMPANY"]
Output: ["HE01", "DN02", "PN03", "CY04"]

Below is my current code:

ls = ["HOMAGE", "DESIGN", "PROTECTION", "COMPANY"]
ser = []

def serialize(lis):
    for l in range(len(lis)):
        ser = lis[l] + str(l)
        return ser

result = serialize(ls)
print(result)

I’ve tried to dissect the array but nothing else solved.

Asked By: danuw

||

Answers:

Here’s a list comprehension approach:

ls = ["HOMAGE", "DESIGN", "PROTECTION", "COMPANY"]
ser = [f"{j[0]}{j[-1]}{i+1:>02}" for i,j in enumerate(ls)]
print(ser)

What did I do above?

  • Using f-strings makes it easier to create strings with variables.
    enumerate(iterable) returns the (index, value) pair of the iterable.
  • j[0] and j[-1] are nothing but the first and last values.
  • i+1:>02 returns the index with a preciding 0. i.e 1 returns 01.
  • +1 since you don’t want 00 as the first but 01.

Edit: Thanks to @ILS

You could also omit +1 and directly start enumerate() with 1

ser = [f"{j[0]}{j[-1]}{i:>02}" for i,j in enumerate(ls, 1)]

Docs:
enumerate()
String Formatting
f-strings

Answered By: The Myth