[英]I want to create elements of a list where each element comes from a satisfied nested for if loop statement
str1 ="John000Doe000123"
list1 = []
for i in str1:
if i == "0":
continue
list1.append(i)
print(list1)
OUTPUT: ['J', 'o', 'h', 'n', 'D', 'o', 'e', '1', '2', '3']
但我想要的 output 是:
OUTPUT: ['John', 'Doe', '123']
您可以在字符“0”處拆分字符串並從那里僅查找有效條目:
str1 ="John000Doe000123"
print([name for name in str1.split('0') if name])
# ['John', 'Doe', '123']
使用循環的簡單解決方案之一是:
str1 ="John000Doe000123"
list1 = []
str2 = ""
for i in str1:
if i == "0":
if str2!="":
list1.append(str2)
str2 = ""
else:
str2 += i
if str2!= "":
list1.append(str2)
print(list1)
只是為了涵蓋所有拆分選項,您還可以使用正則表達式來拆分可變長度的"0"
序列:
>>> import re
>>> re.split(r"0+", str1)
['John', 'Doe', '123']
(在這種情況下,沒有必要使用原始字符串,但這是正則表達式的一個好習慣)
快速簡便,您需要s.split('000')
。
對於可變數量的
0
,請使用其他答案中提到的正則表達式解決方案。
>>> str1 ="John000Doe000123"
>>> str1.split('000')
['John', 'Doe', '123']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.