tags:

views:

106

answers:

3

i have a list:

row=['hi', 'there', 'how', ...........'some stuff is here are ','you']

as you can see row[8]='some stuff is here are '

if the last character is a space i would like to get everything except for the last character like this:

if row[8][len(row[8])-1]==' ':
  row[8]=row[8][0:len(row[8])-2]

this method is not working. can someone suggest a better syntax please?

+3  A: 

Negative indexes count from the end. And slices are anchored before the index given.

if row[8][-1]==' ':
  row[8]=row[8][:-1]
Ignacio Vazquez-Abrams
on the first line: IndexError: string index out of range
i am a girl
Then you're doing something else wrong. Like not checking to see if the length is greater than 0.
Ignacio Vazquez-Abrams
@user2982349-this-is-a-terrible-name: Are you sure row[8] isn't ''?
Thanatos
+5  A: 

So you want it without trailing spaces? Can you just use row[8].rstrip?

Daenyth
Shouldn't it be `row[8].rstrip()`?
MAK
@MAK: You're right of course. I was being lazy and just giving the method name ;)
Daenyth
+3  A: 
row = [x.strip() for x in row]

(if you just want to get spaces at the end, use rstrip)

leoluk
This also gets rid of leading spaces. The OP might not want that. See `rstrip()`.
MAK