John Materum
John Materum

Reputation: 37

How do I find the position of the first occurrence of a letter(from the alphabet) in a string?

For example if the string is

s = "##catgiraffeapluscompscI"

How do I get the output to 2 since the first letter that occurs in this string is at position 2 (c)?

I also want this to be able to work for different strings as well (like a function) which may not have c as their first letter, so I don't want

s.find('c')

Upvotes: 2

Views: 12761

Answers (7)

Nathan
Nathan

Reputation: 1540

the top answer by kelly bundy only works for a happy path where there *is* a letter in the string. Otherwise next() ends up throwing a StopIteration error. This can simply be caught:

try:
  return s.find(next(filter(str.isalpha, s)))
except StopIteration:
  return -1

Upvotes: 1

츄 plus
츄 plus

Reputation: 514

If you don't want to import regex or other modules: the following uses standard library only, will ignore all non-alphabetic characters and give you the position of the first alphabetic character, using the isalpha() method.

foo = "##catgiraffeapluscompscI"

L = len(foo)

vivi = 0
for v in range(1,L):
    if foo[vivi].isalpha():
        print ("First alphabetic character " + foo[vivi] + " at position " + str(vivi))
        break
    vivi = vivi + 1    

Output:

First alphabetic character c at position 2

Upvotes: 1

Zeeshan Qureshi
Zeeshan Qureshi

Reputation: 105

def find_index(input_string,input_value):
    return input_string.index(input_value))
answer = find_index("##catgiraffeapluscompscI", 'c')
print(answer)

Upvotes: -2

codingatty
codingatty

Reputation: 2084

First, Nick's answer is, I think best. But regexes can be tough, and I'm not good with them, so I tend to stay away from them since in my hands they're pretty fragile.

So for what it's worth, here's a short way that doesn't use regexes:

import string
s = "##catgiraffeapluscompscI"
letters_found = [L for L in string.ascii_letters if L in s]
if letters_found:
    first_letter_position = min([s.find(L) for L in letters_found])
else:
    first_letter_position = -1
print(first_letter_position)

Basically, it makes a list of all the letters in your target (empty if there are none in the target); then for each letter that's present in the target, finds the first location; and takes the smallest of that.

But again, Nick's is better if you're comfortable with regexes.

Upvotes: 0

Kelly Bundy
Kelly Bundy

Reputation: 27588

First finding the letter and then its index.

>>> s.find(next(filter(str.isalpha, s)))
2

Upvotes: 10

Nick
Nick

Reputation: 147166

You can use a regex to search for the first letter (a-z or A-Z by using the re.I flag), and if found, return the start value from the match object:

import re

def first_letter(s):
    m = re.search(r'[a-z]', s, re.I)
    if m is not None:
        return m.start()
    return -1

s = "##catgiraffeapluscompscI"
i = first_letter(s)
print(i)

Output:

2

Upvotes: 2

Parakiwi
Parakiwi

Reputation: 611

You can treat a string as a list of characters, and iterate through it until you find a match. This while statement checks for the character, and if it does not exists it stops you falling off the end of the list.

s = "##catgiraffeapluscompscI"
index = 0
search_char = "c"

while (index != len(s)) and (s[index] != search_char):
    index += 1

if index == len(s):
    print("Character not in string")
else:
    print("Character is at position: ", index)

Upvotes: 0

Related Questions