-1

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.

PSR
  • 249
  • 1
  • 10
  • You should explain *why* it is printing that. For example, you don't print the `[abc]` items? Why? Because of the dot? The index? The content? – Mark Jan 16 '22 at 19:33
  • I am failing to see the logic behind what should be extracted from the string and what shouldn't. Like why [xyz] but not [abc] ? – Dionys Jan 16 '22 at 19:34
  • Welcome to [Stack Overflow.](https://stackoverflow.com/ "Stack Overflow") Please be aware this is not a code-writing or tutoring service. We can help solve specific, technical problems, not open-ended requests for code or advice. Please edit your question to show what you have tried so far, and what specific problem you need help with. See the [How To Ask a Good Question](https://stackoverflow.com/help/how-to-ask "How To Ask a Good Question") page for details on how to best help us help you. – itprorh66 Jan 16 '22 at 19:34
  • So, you split the string on "." to get the three parts. Then, you split each part on "," and print the first element of the split. – Tim Roberts Jan 16 '22 at 19:34
  • What is fixed, what is variable in this example? Are the `[abc]` literal? Always identical? – mozway Jan 16 '22 at 19:39

5 Answers5

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

Robert Cotterman
  • 2,213
  • 2
  • 10
  • 19
  • normally people wanna see what you can do, but this is very simplistic. – Robert Cotterman Jan 16 '22 at 19:39
  • since i am learning, i have no idea that something like enumerate even exists, i know it is simple ... now that i am aware of something like Enumerate method i will read more on it and expand my knowledge .. – PSR Jan 16 '22 at 19:42
  • i appreciate your answer – PSR Jan 16 '22 at 19:42
  • Thank you, and keep learning, However i did not catch you had periods and commas. There are a few other techniques that can work for that. – Robert Cotterman Jan 16 '22 at 19:47
  • Don't use built-in names as variable name. – S.B Jan 16 '22 at 19:50
  • I'm sorry but this does not even generate the excepted output. – S.B Jan 16 '22 at 19:51
  • You are correct, I have updated. also he is correct, don't use "list" – Robert Cotterman Jan 16 '22 at 19:54
  • 1
    Thanks, this comment section itself has taught me a lot. – PSR Jan 16 '22 at 19:57
  • The other answers can be helpful too. string manipulation is a big part of learning python. Be aware that regex can be slow if done wrong, so be careful. It is very powerful, but also very hungry, wild cards can get dangerous. So I would recommend learning regex from a fully fledged class before digging deep into it. – Robert Cotterman Jan 16 '22 at 19:58
1

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}")
  • There is a number associated with every print line in the OP's excepted output. – S.B Jan 16 '22 at 19:52
1

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))
S.B
  • 13,077
  • 10
  • 22
  • 49
0

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)
OnY
  • 897
  • 6
  • 12
0

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]
mozway
  • 194,879
  • 13
  • 39
  • 75