简体   繁体   中英

Python: Printing Third Letter of Sentence

def main (): 
    sentence=input("Please enter a sentence:")
    print("Original Sentence:",sentence)
    sentencelenght=len(sentence)
    for i in range(0, sentencelenght, 3): 
        print("Every third letter:", i)
main()

I am at this point and my output is a bunch of numbers, please explain how I can fix this.

Note we have learned for, while loops, if/or statements more basic stuff. Nothing too complicated.

It's because you are using i , not the character at that position. Change that line to this:

print("Every third letter:", sentence[i])

That is not the most efficient way to print every third letter, however. You don't need the loop; just use print(sentence[::3]) . That works because a slice is [start:stop:step] . We are leaving start empty, so it defaults to the beginning. We are leaving stop empty, so it defaults to the end. step , we are defining as 3 , so it goes from the beginning to the end using every third letter.

您可以使用切片来打印每第三个字母(从第一个字母开始):

print(sentence[::3])

I presume you cannot use slicing and need to use your own code, if you want to print every third character starting from the third , start the range an 2 and keep your step of 3 printing each sentence[i] though the loop:

def main ():
    sentence = input("Please enter a sentence:")
    print("Original Sentence:",sentence)
    # start at the third character
    for i in range(2,  len(sentence), 3):
        # access the string by index 
        print("Every third letter:", sentence[i])

Output:

In [2]: main()
Please enter a sentence:001002003
Original Sentence: 001002003
Every third letter: 1
Every third letter: 2
Every third letter: 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM