Home > Net >  Ignore Repeated content in a String in Python
Ignore Repeated content in a String in Python

Time:07-05

I am looking for support to Ignore repeated content in a string.

a= "Item 1.01 Entry the party thereto Item 2.02 Exit Item 4.02 Please go from Item 1.01 Item 5.06 lets have some party "

I want Output as Item 1.01, Item 2.02, Item 4.02, Item 5.06, i have used following code

b=re.split('Item',a)
code=[]
for i in range(0,len(b[1:])):
  code.append('Item'   " "  b[1:][i][1:5])
code

I am getting Ouput as ['Item 1.01', 'Item 2.02', 'Item 4.02', 'Item 1.01','Item 5.06'] while i dont need repeated element which is 'Item 1.01'. Desired output

['Item 1.01', 'Item 2.02', 'Item 4.02','Item 5.06']

Please help

CodePudding user response:

import re

a = "Item 1.01 Entry the party thereto Item 2.02 Exit Item 4.02 Please go from Item 1.01 Item 5.06 lets have some party"

code = []
for i in re.findall(r"Item \d (?:\.\d )?", a):
    if not i in code:
        code.append(i)

print(code)  # ['Item 1.01', 'Item 2.02', 'Item 4.02', 'Item 5.06']
  • Related