-1

Example: I have a file as :
filename1 = "I am a student" (inside filename1 have I am a student )

f = open(filename1)
string = f.read()
spl = re.split('\s|(?<!\d)[,.](?!\d)',string)
f.close

print spl will show: I am a student , but I need the result as [student a am I] could you answer me please... Thanks in advance.

  • 2
    Aside: `f.close` is missing `()` at the end and so the method isn't actually called. It's a good habit to get into writing `with open(filename1) as f:` instead and indenting the next two lines like a for loop -- that idiom will automatically close the file for you when you're done with it, without any need for an explicit `close`. – DSM Nov 22 '12 at 13:21

2 Answers2

3

You can reverse the list with a martian smiley:

spl = spl[::-1]

Or, if you just need an iterator:

spl = reversed(spl)
Community
  • 1
  • 1
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
0
str=['im a student','im a teacher']
list=[]
for x in str:
   new=""
   for y in [x for x in reversed(x.split())]:
       new+=y
       new+=' '
   list.append(new)

print list // ['student a im ', 'teacher a im ']
Darknight
  • 1,132
  • 2
  • 13
  • 31
  • `list` and `str` are both the names of builtins, so shadowing those names with user-defined variables should generally be avoided as it leads to confusion. That's especially true here, where your `str` isn't a string but a list of strings. – DSM Nov 22 '12 at 13:28
  • Yes,I accept your point.But Here i meant to use list instead of reading from a file since reading a line from a file is similar to read a string from a list. This is just I have made an example to make it simple and clear in understanding. – Darknight Nov 22 '12 at 13:49