How to remove leading and trailing spaces from strings in a Python list

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 the last character, such as:

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

this method does not work. can anyone suggest a better syntax please?

+5
source share
3 answers
row = [x.strip() for x in row]

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

+7
source

Negative indices are counted from the end. And the fragments are tied to the pointer.

if row[8][-1]==' ':
  row[8]=row[8][:-1]
+4
source

, , ? row[8].rstrip?

+4

All Articles