相关疑难解决方法(0)

从字符串列表的元素中删除尾随换行符

我必须在表格中列出大量的单词:

['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']
Run Code Online (Sandbox Code Playgroud)

然后使用条带功能,将其转换为:

['this', 'is', 'a', 'list', 'of', 'words']
Run Code Online (Sandbox Code Playgroud)

我以为我写的东西会起作用,但我一直都会收到错误说:

"'list'对象没有属性'strip'"

这是我试过的代码:

strip_list = []
for lengths in range(1,20):
    strip_list.append(0) #longest word in the text file is 20 characters long
for a in lines:
    strip_list.append(lines[a].strip())
Run Code Online (Sandbox Code Playgroud)

python list strip

111
推荐指数
4
解决办法
17万
查看次数

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

我有一个清单:

row=['hi', 'there', 'how', ...........'some stuff is here are ','you']
Run Code Online (Sandbox Code Playgroud)

如你看到的 row[8]='some stuff is here are '

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

if row[8][len(row[8])-1]==' ':
  row[8]=row[8][0:len(row[8])-2]
Run Code Online (Sandbox Code Playgroud)

这种方法不起作用.有人可以提出更好的语法吗?

python

5
推荐指数
1
解决办法
6549
查看次数

标签 统计

python ×2

list ×1

strip ×1