Sep-15-2019, 12:01 PM
(This post was last modified: Sep-15-2019, 12:01 PM by YoungGrassHopper.)
(Sep-15-2019, 09:55 AM)snippsat Wrote: In a ordinary loop it would be like this.
>>> string = 'The quick brown fox jumps over the lazy dog. ' >>> characters = 'aeiou' >>> >>> lst = [] >>> for c in string: ... if c not in characters: ... lst.append(c) ... >>> print(''.join(lst)) Th qck brwn fx jmps vr th lzy dg.So a list comprehension construct make code over in line.
Can also remove the list as it's make agenerator object
first.
>>> g = (c for c in string if c not in characters) >>> g <generator object <genexpr> at 0x03C8C8B0> >>> next(g) 'T' >>> next(g) 'h'See that there is a small difference no[]
,and it still work as''.join()
run thegenerator expressions
.
>>> print(''.join(c for c in string if c not in characters)) Th qck brwn fx jmps vr th lzy dg.
Thanks snippsat
The ordinary loops is much softer on my understanding as I have only worked with a couple of them till date and haven't been taught or tasked to use a for loop as a one liner. the one liners though look more simple as there seems no need for indentation and all that.
Since this thread is named string handling and the use of for loops are being discussed.
I have another task bugging me which I need advice on.
So I have a txt file with a list of names surnames and date of births.
it looks like this:
Orville Wright 21 July 1988
Rogelio Holloway 13 September 1988
Marjorie Figueroa 9 October 1988
Debra Garner 7 February 1988
And so on.
I need to write python code which reads in the data from the list and restructures and prints it in this format:
Name:
Debra Garner
Birthdate:
7 February 1988
My attempt :
f = open doc = f.read() print(doc.replace(' ','\n')) f.close()Now I am getting:
Debra
Surname
21
Aug
1999
Is it possible to refer to the second white space in a line or how would one efficiently go about solving this?