Python 从列表中删除特定字符串会留下它们吗?

标签 python

我正在写一些代码,我想搜索这个列表并删除开头的所有 1。一旦它达到 0,我希望它停止并成为新列表。每当我总共有 13 个字符时,它就会执行我想要的操作 - converted = ("1111111011110") 但是当我有完整的 16 个字符时,converted = ("1111111111011110") 它会离开开头多了两个......

这是我的代码:

converted = ("1111111111011110")
finalL = []
i = 0
for x in converted:
    finalL.append(x)

print(finalL)


for x in finalL:
    if finalL[0] == "1":
        finalL.remove("1")


print(finalL)

现在它打印第一个列表: ['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '0', '1', ' 1', '1', '1', '0']

然后是这个列表:['1', '1', '0', '1', '1', '1', '1', '0']

我希望第二个 print 打印 ['0', '1', '1', '1', '1', '0']

最佳答案

如果您只有一次和零,并且您只关心从第一个零开始及之后的字符串,我会执行如下操作。

string = '1111111110111111110'
first_zero = string.find('0')
new_string = string[first_zero:] #'0111111110'

请注意,这不适用于只有一个的字符串,因为 find 将返回 -1,这将是您的字符串的最后一个字符。因此,您需要确保每次返回 -1 时您的字符串实际上什么都没有。

或者按照您的循环示例:

converted = '1111111110111111110'
finalL = ''

for i,elem in enumerate(converted):
    if elem=='0':
        # if a zero is found, copy the whole string from
        # this position
        finalL = converted[i:]
        break

关于Python 从列表中删除特定字符串会留下它们吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53453333/

相关文章:

python - Python 中的 Streamplot 错误

Python如何确保在模块死亡之前调用对象的 __del__() 方法?

javascript - 将 Python 条件转换为 JavaScript 正则表达式

python - 如何旋转三角形pygame

python - 认证Django

源代码中的 python 模块 - 命名

python - 伯克利咖啡命令行界面

python - 部分转换Python数据框中的列

Python:将多维字典的列表转换为字典键,并进行异常处理

python - makemigrations 未检测到 Django 1.7 中扩展模型的更改