Python | First alphabet index
Last Updated :
05 May, 2023
Sometimes, while working with Python strings we can have a problem in which we need to extract the first index of alpha character from string. This can have application in day-day programming. Lets discuss certain ways in which this task can be performed.
Method #1: Using loop + regex The combination of above functionalities can be used to perform this task. In this, we employ loop to loop through the string and regex is used to filter out for alphabets in characters.
Python3
import re
test_str = "34#$g67fg"
print ( "The original string is : " + test_str)
res = None
temp = re.search(r '[a-z]' , test_str, re.I)
if temp is not None :
res = temp.start()
print ( "Index of first character : " + str (res))
|
Output :
The original string is : 34#$g67fg
Index of first character : 4
Time complexity: O(n), where n is the length of the input string “test_str”.
Auxiliary space: O(1), which means it uses a constant amount of extra memory space, regardless of the size of the input string “test_str”
Method #2: Using find() + next() + filter() + isalpha() The combination of above methods can also be used to perform this task. In this, we check for alphabets using isalpha(). The task of finding element is done by find(). The next() returns the 1st occurrence.
Python3
import re
test_str = "34#$g67fg"
print ( "The original string is : " + test_str)
res = test_str.find( next ( filter ( str .isalpha, test_str)))
print ( "Index of first character : " + str (res))
|
Output :
The original string is : 34#$g67fg
Index of first character : 4
Method #3: Using loop + ord() The combination of above method can be used to solve the task. In this, we iterate over string and check the ascii value with the help of ord method. If the ascii value is in range of alphabets than return the index of character.
Python3
test_str = "3g4#$67fg"
print ( "The original string is : " + test_str)
ans = - 1 ;
for i in test_str:
temp = ord (i)
if ( 65 < = temp < = 90 ) or ( 97 < = temp < = 122 ):
ans = test_str.index(i);
break ;
print ( "Index of first character : " + str (ans))
|
Output:
The original string is : 3g4#$67fg
Index of first character : 1
Method #4: Using index() and without isalpha() method
Python3
test_str = "34#$g67fg"
print ( "The original string is : " + test_str)
alphabets = "abcdefghijklmnopqrstuvwxyz"
res = 0
for i in test_str:
if i in alphabets:
res = test_str.index(i)
break
print ( "Index of first character : " + str (res))
|
Output
The original string is : 34#$g67fg
Index of first character : 4
Time Complexity: O(n)
Auxiliary Space: (n)
Method #5: Using re.search() with ignorecase flag
Python3
import re
test_str = "34#$g67fg"
print ( "The original string is : " + test_str)
res = None
temp = re.search(r '[a-zA-Z]' , test_str)
if temp is not None :
res = temp.start()
print ( "Index of first character : " + str (res))
|
Output
The original string is : 34#$g67fg
Index of first character : 4
Time Complexity: O(n)
Auxiliary Space: O(1)
Method #6: Using a list comprehension and isalpha()
Python3
test_str = "34#$g67fg"
matches = [(i, c) for i, c in enumerate (test_str) if c.isalpha()]
res = matches[ 0 ][ 0 ]
print ( "Index of first character : " + str (res))
|
Output
Index of first character : 4
Time Complexity:
- The list comprehension creates a list of length <= len(test_str) containing only characters that satisfy the condition c.isalpha().
- Indexing the list to get the first pair is a constant-time operation.
- Therefore, the time complexity of this method is O(len(test_str)).
Auxiliary Space:
- The list comprehension creates a new list of length <= len(test_str) containing only characters that satisfy the condition c.isalpha().
- Therefore, the auxiliary space complexity of this method is O(len(test_str)).
Method #7: Using a generator expression and isalpha()
Use the enumerate() function to iterate over the characters in test_str along with their indices. The isalpha() method is then called on each character to determine if it is an alphabet. The generator expression (i for i, c in enumerate(test_str) if c.isalpha()) produces a sequence of indices where the corresponding characters are alphabets. The next() function is then used to retrieve the first index from this sequence, or -1 if the sequence is empty.
Python3
test_str = "3g4#$67fg"
ans = next ((i for i, c in enumerate (test_str) if c.isalpha()), - 1 )
print ( "Index of first character : " + str (ans))
|
Output
Index of first character : 1
Time Complexity: O(n), where n is the length of the string.
Auxiliary space: O(1)
Method 8 : Using lambda function and filter() method
- Define a lambda function that returns True if the given character is an alphabet, else False.
- Use the “filter()” method to filter out non-alphabetic characters from the given string “test_str”.
- Convert the filtered result to a list.
- If the list is not empty, print the index of its first element in the original string “test_str” using the “index()” method.
Python3
test_str = "34#$g67fg"
print ( "The original string is : " + test_str)
alpha_list = list ( filter ( lambda char: char.isalpha(), test_str))
if alpha_list:
res = test_str.index(alpha_list[ 0 ])
else :
res = None
print ( "Index of first character : " + str (res))
|
Output
The original string is : 34#$g67fg
Index of first character : 4
The time complexity of the above code is O(n), where n is the length of the given string “test_str”.
The auxiliary space used by the code is O(m), where m is the number of alphabetic characters in the string “test_str”.
Similar Reads
Python - Index Frequency Alphabet List
We are given a list we need to count the frequency of each alphabets from the list. For Example we have a list a = ['a', 'b', 'a', 'c', 'b', 'a'] .The output should be having count of each alphabets = {'a':3, 'b':2 ,'c':1 } . For finding frequency of each alphabet we can use dictionary, Counter clas
2 min read
Print Alphabets till N-Python
Printing Alphabets till N in Python involves generating a sequence of uppercase or lowercase letters starting from 'A' (or 'a') up to the N-th letter of the alphabet. For example, if N = 5, the output should be: 'A B C D E'. Let's explore a few ways to implement this in a clean and Pythonic way. Usi
2 min read
Python - Index Mapping Cypher
Sometimes, while working with Python, we can have problems in security or gaming domain, in which we need to create certain cyphers, they can be different types of. This includes Index Mapping Cypher in which we pass a string of integers and we get element characters in that order. Lets discuss cert
3 min read
Python - Consecutive Alphabetic Occurrence
Sometimes, while working with Strings, we can have a problem in which we need to check whether we can find occurrence of characters consecutive and according to English alphabets. This kind of problem can occur in school programming and day-day programming. Lets discuss certain ways in which this ta
4 min read
Assign Alphabet to Each Element - Python
The task of assigning an alphabet to each element in a list involves transforming the elements of the list into corresponding alphabetic characters, where each unique element is mapped to a unique letter. In this task, the goal is to iterate through a list and assign a letter from the alphabet to ea
4 min read
Alphabet Pattern Programs in Python
Pattern programs help improve logic and problem-solving in coding. Using Python loops and the ASCII system, we can print alphabet-based patterns like triangles, pyramids and more. ASCII Important Points: Uppercase letters: A-Z: ASCII 65â90Lowercase letters: a-z: ASCII 97â122Use chr() to convert an A
6 min read
Python | Extract Strings with only Alphabets
In Python, extracting strings that contain only alphabetic characters involves filtering out any strings that include numbers or special characters. The most efficient way to achieve this is by using the isalpha() method, which checks if all characters in a string are alphabetic. [GFGTABS] Python li
3 min read
Python - Like Index Common characters
Sometimes we come across this type of problem in which we require to intersect each element of one list with the other. This type of problems usually occurs in developments in which we have the combined information, like names and surnames in different lists. Letâs discuss certain ways in which this
3 min read
Difference Between find( ) and index( ) in Python
Both methods are used to locate the position of a substring within a string but the major difference between find() and index() methods in Python is how they handle cases when the substring is not found. The find() method returns -1 in such cases, while index() method raises a ValueError. Example of
2 min read
Python - Filter rows with only Alphabets from List of Lists
Given Matrix, write a Python program to extract rows which only contains alphabets in its strings. Examples: Input : test_list = [["gfg", "is", "best"], ["Geeks4Geeks", "good"], ["Gfg is good"], ["love", "gfg"]] Output : [['gfg', 'is', 'best'], ['love', 'gfg']] Explanation : All strings with just al
5 min read