2

I have a word and I want to split each character from a word. I use FOR IN loop to split the characters. During split I want to detect first and last characters. I use a variable count and count is initialized to 0. If count=1 then it is first character. But similarly how can I detect the last character in FOR IN loop in python

    count=0;
    for w in word:
        count++
        if count==1:
            #first character
cs95
  • 379,657
  • 97
  • 704
  • 746
Muthu
  • 189
  • 3
  • 7
  • 18

3 Answers3

7

Why not just use enumerate? It's meant for this very purpose.

for i, w in enumerate(word):
    if i in {0, len(word)-1}:
        ... # do something

You can get rid of the count variable now.

cs95
  • 379,657
  • 97
  • 704
  • 746
1
if count == len(word):
   #last 
GuangshengZuo
  • 4,447
  • 21
  • 27
1

If you just want to get the first and last characters, you can use the first and last index.

s = 'word'
s[0] >>> 'w'
s[-1] >>> 'd'
jabargas
  • 210
  • 1
  • 3