作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个文本文件test.txt
,里面有'a 2hello 3fox 2hen 1dog'
。
我想读取文件,然后将所有项目添加到列表中,然后 strip
整数,这样列表看起来像这样 'a hello fox hen dog'
我试过了,但我的代码不工作。结果是 ['a 2hello 3foz 2hen 1dog']
。谢谢
newList = []
filename = input("Enter a file to read: ")
openfile = open(filename,'r')
for word in openfile:
newList.append(word)
for item in newList:
item.strip("1")
item.strip("2")
item.strip("3")
print(newList)
openfile.close()
最佳答案
来自 python Doc
str.strip([chars])
Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:
Strip 不会修改字符串,在删除提到的字符后返回字符串的副本。
>>> text = '132abcd13232111'
>>> text.strip('123')
'abcd'
>>> text
'132abcd13232111'
你可以试试:
out_put = []
for item in newList:
out_put.append(item.strip("123"))
如果你想删除所有 123
然后使用正则表达式 re.sub
import re
newList = [re.sub('[123]', '', word) for word in openfile]
注意:这将从每一行中删除所有 123
关于python - 如何在 python 中使用 strip(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33007218/
我是一名优秀的程序员,十分优秀!