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

Question:

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.

Asked By: Akshay Agantham

||

Answers:

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])
Answered By: codester_09

By slicing you can achieve your desired output..!

Example:-

word=input("Enter the word: ")
print("Word after slicing: "+word[1:-1]+" Length of word: "+str(len(word[1:-1])))

Output:-

Enter the word: Blockchain
Word after slicing: lockchai Length of word: 8
Answered By: Yash Mehta

With input = ‘blockchain’, you can use input[-1]

Answered By: lamiye19
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.