我需要以下的python代码,我的老师没有通过

问题描述 投票:0回答:1

编写一个程序,返回任何单词的第一个和最后一个字母,以及 在屏幕上打印。

我需要指导才能正确使用代码或允许我以良好的方式开发所需内容的代码,从而不使用 chatgpt 等工具

python python-2.7
1个回答
-1
投票

这是你需要的吗?:

word = "hello" #word
listedword = list(word) #list("hello") returns a list: ['h','e','l','l','o']
lengthofword = len(listedword) #len(list) returns the length of a list
firstletter = listedword[0] #first letter of the word at index 0
lastletter = listedword[lengthofword - 1] #-1 because indexing starts at 0
print(f"first letter: {firstletter}, last letter: {lastletter}") #using an f string to insert the first and last letters

© www.soinside.com 2019 - 2024. All rights reserved.