Shantanu
Shantanu

Reputation: 867

Python String: How to parse string and find specific String index?

I want to create a list of tuples, where I want:

# String
input= "M   i     n        d"

# List of tuple
output = [(0, 3), (4, 9), (10, 18), (19, 19)]

I was able to write this logic(with an error in the last tuple), but feel that there must be a smarter way of writing this. Any idea?

string = "M   i     n        d"
coltuple = []

for a in string:

    if a.isalpha() == True:
        start = string.index(a)
        next_string = string[(start + 1) :]

        if next_string:

            for b in next_string:

                if b.isalpha() == True:
                    end = string.index(b) - 1
                    print("End:", end)
                    break
        else:
            end = len(string) - 1

        coltuple += [(start, end)]

print(coltuple)

Upvotes: 0

Views: 280

Answers (2)

Chris Charley
Chris Charley

Reputation: 6598

This could be solved using the re module.

import re

L = []
string = "M   i     n        d"

pat = re.compile(r'\S+\s*')

for token in pat.finditer(string):
    L.append((token.start(), token.end()-1))

print(L)

Prints:

[(0, 3), (4, 9), (10, 18), (19, 19)]

If you are going to use these values to index into the string, you might be better off using token.end() rather than token.end()-1.

Note: removed capturing parentheses from the regular exp. It was r'(\S+\s*)

Upvotes: 1

Dejan Petrovic
Dejan Petrovic

Reputation: 71

This is what I came up with:

inputString= "M   i     n        d"

alphaIndexes = []
alphaTuples = []

# Loop over range based on length of input
for i in range(0, len(inputString)):
    # if its alpha
    if inputString[i].isalpha() == True:
        print("Alpha at {}".format(i))
        # append it to list of indexes
        alphaIndexes.append(i)

# Loop over range based on length of all found alphas
# minus one since we will create pairs
for i in range(0, len(alphaIndexes)-1):
    # Append to list o alpha tuples tuple of
    # current index and next index but substract that next one by one
    alphaTuples.append((alphaIndexes[i], alphaIndexes[i+1]-1))

print(alphaTuples)

Upvotes: 1

Related Questions