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']
but the output that I want is:
OUTPUT: ['John' , 'Doe' , '123']
CodePudding user response:
You could split your string at character '0' and seek only valid entries from there:
str1 ="John000Doe000123"
print([name for name in str1.split('0') if name])
# ['John', 'Doe', '123']
CodePudding user response:
One of the simple solution using loop will be:
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)
CodePudding user response:
Just to cover all the splitting options, you can also do this with regular expressions to split on variable length sequences of "0"
:
>>> import re
>>> re.split(r"0 ", str1)
['John', 'Doe', '123']
(in this case it's not necessary to use a raw string but it's a good habit for regexes)
CodePudding user response:
Quick and easy, you want s.split('000')
.
For variable number of
0
's, use a regex solution as mentioned by other answer.
>>> str1 ="John000Doe000123"
>>> str1.split('000')
['John', 'Doe', '123']