簡體   English   中英

如何從Python列表中的字符串中刪除前導和尾隨空格

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

我有一個清單:

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

正如你可以看到row[8]='some stuff is here are '

如果最后一個字符是一個空格我想得到除了最后一個字符之外的所有字符:

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

這種方法不起作用。 有人可以提出更好的語法嗎?

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

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

負指數從最后開始計算。 並且在給出索引之前錨定切片。

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

所以你想要它沒有尾隨空格? 你能用row[8].rstrip嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM