0

I have the following text file:

"""['    Hoffa remains      Allen Iverson      Bill Cosby      WWE Payback results           Juneteenth shooting      Miss Utah flub      Octopus pants      Magna Carta Holy Grail      China supercomputer      Sibling bullying  ']"""

I would like to create a list from it and apply a function to each name

this is my code so far:

listing = open(fileName, 'r')
lines = listing.read().split(',')
for line in lines:
    #Function
viraptor
  • 33,322
  • 10
  • 107
  • 191
user2493744
  • 65
  • 1
  • 1
  • 7
  • You're splitting the text using `,` as the delimiter, but it looks like six spaces or would be more appropriate for your file. – ASGM Jun 21 '13 at 14:31
  • 2
    I don't see any commas in your input text. Are the `"""['` characters literally part of your input file? – Martijn Pieters Jun 21 '13 at 14:31

2 Answers2

2

Strip out character like """['] first from the start and end of the string using str.strip, now split the resulting string at six spaces(' '*6). Splitting returns a list, but some items still have traling and leading white-spaces, you can remove them using str.strip again.

with open(fileName) as f:
    lis =  [x.strip() for x in f.read().strip('\'"[]').split(' '*6)]
    print lis
...     
['Hoffa remains', 'Allen Iverson', 'Bill Cosby', 'WWE Payback results', 'Juneteenth shooting', 'Miss Utah flub', 'Octopus pants', 'Magna Carta Holy Grail', 'China supercomputer', 'Sibling bullying']

Applying function to the above list:

List comprehension:

[func(x) for x in lis]

map:

map(func, lis)
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
1

I would first refer you to some other similar posts: similar post

And you can't use a coma here you don't have a coma between the data you wan't to separate. This function splits the string you have into substring depending on the delimiter you gave it: a coma ','.

Community
  • 1
  • 1
user2497624
  • 159
  • 9