0

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

  • first element of tuple = index of alphabet
  • second element of tuple = index of whitespace before the next alphabet
# 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)

2 Answers 2

1

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*)

Sign up to request clarification or add additional context in comments.

Comments

1

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)

3 Comments

I like your solution too, as it is readable. Although, the last tuple (19, 19) is missing from output.
My bad I believed you are searching other logic because of error.
Yes, more improved logic with that last one added in there too.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.