Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 563
Alex Gordon Avatar asked Sep 01 '10 18:09

Alex Gordon


People also ask

How do I remove leading and trailing space from a list in Python?

strip() Python String strip() function will remove leading and trailing whitespaces. If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.

What does TRIM () do in Python?

Python trim essentially means removing whitespaces from a string. While dealing with strings in files or user input strings, whitespaces are a common problem. Since Python considers whitespaces as a character, they would also be printed in case you decide to print the string.

Which method is used to remove leading and trailing?

Use the Trim() method to remove leading and trailing whitespace from a string.


1 Answers

row = [x.strip() for x in row]

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

like image 110
leoluk Avatar answered Oct 13 '22 01:10

leoluk