How to find the first and last of one of several characters in a list of strings? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How to find the first and last of one of several characters in a list of strings? (/thread-27301.html) |
How to find the first and last of one of several characters in a list of strings? - tadsss - Jun-02-2020 So I have a list of strings such as this: my_list=["---abcdefgh----abc--","--abcd-a--","----------abcdefghij----ab-","-abcdef---a-","----abcdefghijklm----abc--"] I want, for each string, to retrieve the position where the first and last letters appear. Or in other words, to find the position of the first character that isn't a "-" and the position of the last character that isn't a "-". It would be perfect if I could save the result as two lists, one of the first positions and another for the last. I've tried using find() at least for the first position but since the character I'm trying to find is one of several letters, I don't know how to do it. The output I wanted was something like this: first_positions=[3,2,10,1,4] last_positions=[17,7,25,11,23] Thanks in advance for any answer RE: How to find the first and last of one of several characters in a list of strings? - buran - Jun-02-2020 you can use re moduleyou can iterate over each string and find at what position is the first/last char if start and end chars are always '-' you can lstrip /rstrip it and see the change in len
RE: How to find the first and last of one of several characters in a list of strings? - bowlofred - Jun-02-2020 I like using re for this, since it can find the element and give you the index directly.>>> mylist = ["---abcdefgh----abc--","--abcd-a--","----------abcdefghij----ab-","-abcdef---a-","----abcdefghijklm----abc--"] >>> [re.search(r"[^-]", x).start() for x in mylist] [3, 2, 10, 1, 4] >>> [re.search(r"[^-]-*$", x).start() for x in mylist] [17, 7, 25, 10, 23] |