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
  Find Common Elements in 2 list quest 4 620 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 921 Dec-11-2020, 07:07 PM
Last Post: tester_V
  Find _ in a list 1234 15 1,367 Dec-01-2020, 07:53 PM
Last Post: bowlofred
  Trying to find first 2 letter word in a list of words Oldman45 7 1,056 Aug-11-2020, 08:59 AM
Last Post: Oldman45
  Introduction to escaping characters in strings Geelong_crazy 1 871 Jul-18-2020, 06:58 PM
Last Post: DT2000
  Remove escape characters / Unicode characters from string DreamingInsanity 5 3,172 May-15-2020, 01:37 PM
Last Post: snippsat
  Find index value in List Martin2998 3 945 May-12-2020, 02:17 PM
Last Post: deanhystad
  Replacing characters in a string with a list cjms981 1 789 Dec-30-2019, 10:50 PM
Last Post: micseydel
  How to find something in a list using its index rix 1 782 Dec-20-2019, 04:12 PM
Last Post: stullis
  Iterating through a list of strings Ash_Ren 1 765 Nov-22-2019, 08:30 PM
Last Post: buran

Forum Jump:

User Panel Messages

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