[英]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. 请注意,我们已经为while循环学习了if / or语句,这是更基本的内容。 Nothing too complicated.
没什么复杂的。
It's because you are using i
, not the character at that position. 这是因为您使用的是
i
,而不是该位置的字符。 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])
. 只需使用
print(sentence[::3])
。 That works because a slice is [start:stop:step]
. 之所以可行,是因为切片是
[start:stop:step]
。 We are leaving start
empty, so it defaults to the beginning. 我们将
start
保留为空,因此默认为开始。 We are leaving stop
empty, so it defaults to the end. 我们将
stop
保留为空,因此默认为末尾。 step
, we are defining as 3
, so it goes from the beginning to the end using every third letter. step
,我们将其定义为3
,因此它从头到尾使用第三个字母。
您可以使用切片来打印每第三个字母(从第一个字母开始):
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: 我假设您不能使用切片,而需要使用自己的代码,如果您要从第三个字符开始打印每第三个字符,请将范围从
2
开始,并保持3步通过循环打印每个sentence[i]
:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.