Issue
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.
Solution
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]
andj[-1]
are nothing but the first and last values.i+1:>02
returns theindex
with a preciding 0. i.e1
returns01
.+1
since you don't want00
as the first but01
.
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
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.