我这里有2个字符串:
line= ['ABDFDSFGSGA', '32\n']
line= ['NBMVA\n']
Run Code Online (Sandbox Code Playgroud)
如何\n从这些字符串的末尾删除.我已经尝试了rstrip(),strip()但我仍然无法\n从字符串中删除.我可以帮忙删除它吗?
您需要从列表中访问要删除的元素:
line= ['ABDFDSFGSGA', '32\n']
#We want to strip all elements in this list
stripped_line = [s.rstrip() for s in line]
Run Code Online (Sandbox Code Playgroud)
你可能做错了什么,就是简单地打电话line[1].rstrip().这不起作用,因为该rstrip方法不能在原地工作,但会返回一个被剥离的新字符串.
例:
>>> a = 'mystring\n'
>>> a.rstrip()
Out[22]: 'mystring'
>>> a
Out[23]: 'mystring\n'
>>> b = a.rstrip()
>>> b
Out[25]: 'mystring'
Run Code Online (Sandbox Code Playgroud)
小智 6
行的类型是list,因此您不能应用任何strip方法.strip方法适用于字符串.
在那里,您需要遍历列表并rstrip()对该列表中存在的每个字符串应用方法.
>>> line= ['ABDFDSFGSGA', '32\n']
>>> map(str.rstrip, line)
['ABDFDSFGSGA', '32']
Run Code Online (Sandbox Code Playgroud)
您可以使用 a.replace('\n','')但请注意,这将删除所有实例\n如果您想对整个列表执行此操作,您可以这样做:
line = [i.replace('\n','') for i in line]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20183 次 |
| 最近记录: |