gpt4 book ai didi

python - 如何在 python 中使用 strip()

转载 作者:行者123 更新时间:2023-11-28 19:48:26 26 4
gpt4 key购买 nike

我有一个文本文件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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com