1

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
  • 330,695
  • 80
  • 606
  • 657
Muthu
  • 209
  • 2
  • 7
  • 15

3 Answers3

6

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
  • 330,695
  • 80
  • 606
  • 657
1
if count == len(word):
   #last 
GuangshengZuo
  • 4,017
  • 18
  • 24
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
  • 200
  • 3