specific characters printing with Python

149 views Asked by At

given a string as shown below,

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

how to print it like shown below ?

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

The original string will always maintain the above-mentioned format.

5

There are 5 answers

9
Robert Cotterman On BEST ANSWER

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

1
Mohammad Khoshbin On

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}")
0
OnY On

You can use RegEx:

import regex as re
pattern=r"(\[[a-zA-Z]*\])\,\[[a-zA-Z]*\]\.?"
results=re.findall(pattern, '[xyx],[abc].[cfd],[abc].[dgr],[abc]')
print(results)
1
S.B On

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))
0
mozway On

Using re.findall:

import re

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

print('\n'.join(f'{i+1}.{x}' for i,x in
                enumerate(re.findall(r'(\[[^]]+\])(?=,)', s))))

Output:

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