[tex]\sf \red{ Question-}[/tex]
Write a function in Python to parse a string such that it accepts a parameter- an encoded string. This encoded string will contain a first name, last name, and an id. You can separate the values in the string by any number of zeros. The id will not contain any zeros. The function should return a Python dictionary with the first name, last name, and id values. For example, if the input would be "John000Doe000123". Then the function should return: { "first_name": "John", "last_name": "Doe", "id": "123" }
[tex]\sf \red{ Note-}[/tex]
• Answer it correctly.
• Please don't spam.
• Need full explanation.
• Don't give any irrelevant answers.
━━━━━━━━━━━━━━━━━━━━━━━━━
Answers & Comments
Verified answer
def indiavsafg_indiawins():
x=str(input("Enter string:"))
p=x[::-1]
a=""
for i in range(len(p)):
if p[i]=="0":
a=a+p[0:i]
b_id=a[::-1]
c_firstname=""
for i in range(len(x)):
if x[i]=="0":
c_firstname=c_firstname+x[0:i]
e=x.replace(c_firstname,"")
w=""
o_lastname=""
for i in range(len(e)):
if e[i].lower() in "abcdefghijklmnopqrstuvwxyz":
w=e[i::]
for j in range(len(w)):
if w[j]=="0":
o_lastname=w[0:j]
finaldict={"first_name": c_firstname, "last_name": o_lastname, "id": b_id}
return finaldict
___________________________
We are taking the string as input to variable x and variable p is reversing the string. Now we are taking the numbers from the reversed string till we encounter any zero as string a and then reversing the string a to obtain the id value. (b_id)
Similarly we get the first name by taking the section of the string from the start till the first zero is encountered and this is assigned to c_firstname
Now we are replacing the first name of the string x with a blank string and then string x starts with the zeroes and then the characters of the last name and so on.
string w is from the characters of the last name to the end.
In string w, we are finding the index where the zeroes start from and the section of the string before that forms the last name. (o_lastname)
Finally the three strings containing the first name (c_firstname), (o_lastname) and (b_id) are added to the dictionary finaldict and it's returned.