Python Forum
How to find the first and last of one of several characters in a list of strings?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to find the first and last of one of several characters in a list of strings?
So I have a list of strings such as this:


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:


Thanks in advance for any answer
you can use re module
you 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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

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--"]
>>> ["[^-]", x).start() for x in mylist]
[3, 2, 10, 1, 4]
>>> ["[^-]-*$", x).start() for x in mylist]
[17, 7, 25, 10, 23]

Possibly Related Threads…
Thread Author Replies Views Last Post
  read a text file, find all integers, append to list oldtrafford 6 145 1 hour ago
Last Post: deanhystad
  find some word in text list file and a bit change to them RolanRoll 3 310 Jun-27-2022, 01:36 AM
Last Post: RolanRoll
  How to find the second lowest element in the list? Anonymous 3 351 May-31-2022, 01:58 PM
Last Post: Larz60+
  Splitting strings in list of strings jesse68 3 657 Mar-02-2022, 05:15 PM
Last Post: DeaD_EyE
  Find if chain of characters or number Frankduc 4 736 Feb-11-2022, 01:55 PM
Last Post: Frankduc
  Python Program to Find the Total Sum of a Nested List vlearner 8 1,081 Jan-23-2022, 07:20 PM
Last Post: menator01
  Find the highest value of a list Menthix 4 832 Oct-29-2021, 02:32 PM
Last Post: Menthix
  Find Common Elements in 2 list quest 4 1,609 Apr-14-2021, 03:57 PM
Last Post: quest
  List of error codes to find (and count) in all files in a directory tester_V 8 2,092 Dec-11-2020, 07:07 PM
Last Post: tester_V
  Find _ in a list 1234 15 3,014 Dec-01-2020, 07:53 PM
Last Post: bowlofred

Forum Jump:

User Panel Messages

Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020