specific characters printing with Python

Solution 1:

I did not realize you had periods and commas... that adds a bit of trickery. You have to split on the periods too

I would use something like this...

list_to_parse = "[xyx],[abc].[cfd],[abc].[dgr],[abc]"

count = 0
for  i in list_to_parse.split('.'):
    for j in i.split(','):
        string = str(count + 1) + "." + j
        if string:
            count += 1
            print(string)
        string = None

Another option is split on the left bracket, and then just re-add it with enumerate - then strip commas and periods - this method is also probably a tiny bit faster, as it's not a loop inside a loop

list_to_parse = "[xyx],[abc].[cfd],[abc].[dgr],[abc]"

for index, i in enumerate(list.split('[')):
    if i:
        print(str(index) + ".[" + i.rstrip(',.'))

also strip is really "what characters to remove" not a specific pattern. so you can add any characters you want removed from the right, and it will work through the list until it hits a character it can't remove. there is also lstrip() and strip()

string manipulation can always get tricky, so pay attention. as this will output a blank first object, so index zero isn't printed etc... always practice and learn your needs :D

Solution 2:

You can use split() function:

a = "[xyx],[abc].[cfd],[abc].[dgr],[abc]"

desired_strings = [i.split(',')[0] for i in a.split('.')]

for i,string in enumerate(desired_strings):
    print(f"{i+1}.{string}")

Solution 3:

This is just a fun way to solve it:

lst = "[xyx],[abc].[cfd],[abc].[dgr],[abc]"

count = 1
var = 1
for char in range(0, len(lst), 6):
    if var % 2:
        print(f"{count}.{lst[char:char + 5]}")
        count += 1
    var += 1

output:

1.[xyx]
2.[cfd]
3.[dgr]

explanation : "[" appears in these indexes: 0, 6, 12, etc. var is for skipping the next pair. count is the counting variable.


Here we can squeeze the above code using list comprehension and slicing instead of those flag variables. It's now more Pythonic:

lst = "[xyx],[abc].[cfd],[abc].[dgr],[abc]"

lst = [lst[i:i+5] for i in range(0, len(lst), 6)][::2]

res = (f"{i}.{item}" for i, item in enumerate(lst, 1))

print("\n".join(res))