[英]How to remove first letter and last letter of a string of unknown length by excluding string characters?
编写一个程序,读取单词并打印单词的长度,不包括第一个和最后一个字符。
样本输入:区块链。 输出:8(通过排除字符串的第一个和最后一个字符。)
我尝试获取字符串的第一个字母并得到它但无法获取它的最后一个字母,因为字符串的长度未知。
从字符串的实际长度减去 2。
print(len(string)-2)
或者,如果您想要没有第一个和最后一个字符的字符串。
print(string[1:-1])
通过切片,您可以获得所需的输出..!
例子:-
word=input("Enter the word: ")
print("Word after slicing: "+word[1:-1]+" Length of word: "+str(len(word[1:-1])))
输出:-
Enter the word: Blockchain
Word after slicing: lockchai Length of word: 8
使用 input = 'blockchain',您可以使用 input[-1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.