# Python – Character coordinates in Matrix

• Last Updated : 30 Dec, 2020

Sometimes, while working with Python data, we can have a problem in which we need to extract all the coordinates in Matrix, which are characters. This kind of problem can have potential application in domains such as web development and day-day programming. Let’s discuss certain ways in which this task can be performed.

Input : test_list = [‘1G’, ’12F’, ‘231G’]
Output : [(0, 1), (1, 2), (2, 3)]

Input : test_list = [‘G’, ‘F’, ‘G’]
Output : [(0, 0), (1, 0), (2, 0)]

Method #1 : Using enumerate() + list comprehension + isalpha()
The combination of above functions can be used to solve this problem. In this, we perform the task of working with indices using enumerate and characters filtering is done using isalpha().

 # Python3 code to demonstrate working of # Character coordinates in Matrix# Using enumerate() + list comprehension + isalpha()          # initializing listtest_list = ['23f45.;4d', '5678d56d', '789', '5678g']  # printing original listprint("The original list is : " + str(test_list))  # Character coordinates in Matrix# Using enumerate() + list comprehension + isalpha()res = [(x, y) for x, val in enumerate(test_list)         for y, chr in enumerate(val) if chr.isalpha()]    # printing result print("Character indices : " + str(res))

Output :

The original list is : ['23f45.;4d', '5678d56d', '789', '5678g']
Character indices : [(0, 2), (0, 8), (1, 4), (1, 7), (3, 4)]

Method #2 : Using regex() + loop
The combination of above functions can be used to solve this problem. In this, we perform task of filtering alphabets using regex expressions. Just returns the first occurrence of character in each string.

 # Python3 code to demonstrate working of # Character coordinates in Matrix# Using regex() + loopimport re          # initializing listtest_list = ['23f45.;4d', '5678d56d', '789', '5678g']  # printing original listprint("The original list is : " + str(test_list))  # Character coordinates in Matrix# Using regex() + loopres = []for key, val in enumerate(test_list):    temp = re.search('([a-zA-Z]+)', val)    if temp :        res.append((key, temp.start()))          # printing result print("Character indices : " + str(res))

Output :

The original list is : ['23f45.;4d', '5678d56d', '789', '5678g']
Character indices : [(0, 2), (1, 4), (3, 4)]

My Personal Notes arrow_drop_up