Search code examples
pythonstringcharacter

How to remove first letter and last letter of a string of unknown length by excluding string characters?


To write a program that reads word and prints length of a word excluding the first and last character.

Sample: input:Blockchain.
Output:8(by excluding first and last char of string.)

I tried getting the first letter of string and got it but unable to get it's last letter since string is of unknown length.


Solution

  • Just minus 2 from the actual length of the string.

    print(len(string)-2)
    

    If your string has characters less than 2 then the above one returns the negative length.

    Then use this one.

    
    length = max(len(string) - 2, 0)
    print(length)
    # This will convert negative numbers to 0. Because 0 is greater than negative numbers.
    
    
    

    Or if you want the string without the first and last character.

    print(string[1:-1])