-1

I have this string, in which the first word is the name, the second in the given name and the third is the age:

'Snow,John,21\nLincoln,Abraham,31\nGates,Bill,29'

For each person I would like to extract something like this:

'Name: ___ | Given name: ___ | Age: ___'

I was thinking to split the string and after that to run through it with For. But I am new to Python and I got stuck here. Do you have any ideas? Thanks!

Yevhen Kuzmovych
  • 10,940
  • 7
  • 28
  • 48
  • 3
    your plan sounds fine, you should have a go at writing it on your own first – Sayse Feb 28 '20 at 12:36
  • 2
    Can you show us what you tried so that we can help you? – Thomas Schillaci Feb 28 '20 at 12:36
  • 2
    Can you write the code you used? You have a nice approach - go ahead! – Yanirmr Feb 28 '20 at 12:37
  • 1
    I'd just redirect you to useful sources on how to [split](https://www.w3schools.com/python/ref_string_split.asp) a string, [loop through](https://www.w3schools.com/python/python_for_loops.asp) result, and [format](https://www.geeksforgeeks.org/python-format-function/) a new string as you'd need it. – Yevhen Kuzmovych Feb 28 '20 at 12:42
  • Does this answer your question? [Split a string by spaces -- preserving quoted substrings -- in Python](https://stackoverflow.com/questions/79968/split-a-string-by-spaces-preserving-quoted-substrings-in-python) – Meruemu Feb 28 '20 at 13:08

1 Answers1

0

based on your approach, you need to split the string twice. Firstly for every record and then for every attribute.

 str = 'Snow,John,21\nLincoln,Abraham,31\nGates,Bill,29'

 #Split the original string to lines/records by newline character
 for man in (str.split("\n")): 
     #Split every record for attribute 
     name, given_name, age = man.split(",")
     print("Name: " + name + "| Given Name: " + given_name + "| Age: " + age)
Yanirmr
  • 923
  • 8
  • 25