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

2024-09-22 16:31:45 发布

您现在位置: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','0','1','1','1','1','0']

但是下面的列表:['1','1','0','1','1','1','1','0']

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


Tags: 代码in密码列表forif字符remove
1条回答
网友
1楼 · 发布于 2024-09-22 16:31:45

如果您只有once和zero,并且您只关心第一个zero及其后的字符串,我将执行以下操作

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

请注意,这不适用于只有一个字符的字符串,因为find将返回-1,这将是字符串的最后一个字符。因此,您需要确保每次返回a-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

相关问题 更多 >