Home > Mobile >  How to colon word extract the text? python
How to colon word extract the text? python

Time:05-26

data =['ram: 1321214124234','cghsdghfdgh balu:reddy', 'E: [email protected]']

this type out put i know = ['ram', 'balu', 'E']

out_put = ['ram:', 'balu:', 'E:'] # i expected this type only

CodePudding user response:

for each element in list first perform split on ':', then split on ' ' and keep last in case of multiple spaces and finally append ':'

out_put = [x.split(':')[0].split(' ')[-1]   ':' for x in data]

CodePudding user response:

You can use the regex library to do this.

import re

regex = r"[ ]*(\w )[ ]*:[ ]*(\w )[ ]*"

test_strs = ["ram: 1321214124234", "cghsdghfdgh balu:reddy", "E: [email protected]"]
for test_str in test_strs:
    matches = re.finditer(regex, test_str, re.MULTILINE)

    for matchNum, match in enumerate(matches, start=1):
        
        print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))
        
        for groupNum in range(0, len(match.groups())):
            groupNum = groupNum   1
            
            print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

In this code, we navigate the list of words. In words, we look for them using the pattern written in this text and print the output of each word.

Example output:

Match 1 was found at 0-18: ram: 1321214124234
Group 1 found at 0-3: ram
Group 2 found at 5-18: 1321214124234
Match 1 was found at 11-22:  balu:reddy
Group 1 found at 12-16: balu
Group 2 found at 17-22: reddy
Match 1 was found at 0-8: E: reddy
Group 1 found at 0-1: E
Group 2 found at 3-8: reddy
  • Related