简体   繁体   English

如何从Python列表中的字符串中删除前导和尾随空格

[英]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 ' 正如你可以看到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? 有人可以提出更好的语法吗?

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

(如果你只是想在最后获得空格,请使用rstrip

Negative indexes count from the end. 负指数从最后开始计算。 And slices are anchored before the index given. 并且在给出索引之前锚定切片。

if row[8][-1]==' ':
  row[8]=row[8][:-1]

So you want it without trailing spaces? 所以你想要它没有尾随空格? Can you just use row[8].rstrip ? 你能用row[8].rstrip吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM