[英]Write programs that read a line of input as a string and print every second letter of the string in Python
Write programs that read a line of input as a string and print every second letter of the string in Python?编写将一行输入读取为字符串并在 Python 中打印字符串的每个第二个字母的程序?
So far I have written:到目前为止,我已经写了:
string=input('Enter String: ')
for char in range(0,len(string),2):
print(len(char))
if i input a string: qwerty
如果我输入一个字符串: qwerty
it should print " qet
"它应该打印“ qet
”
You need to keep it much simpler than this.你需要让它比这简单得多。 If you enter a word and are looking to slice it at a specific point, use slicing.如果您输入一个单词并希望在特定点对其进行切片,请使用切片。
Your criteria: qwerty it should print "qet"
您的标准: qwerty it should print "qet"
So, you are looking to print every second letter:因此,您希望每隔一个字母打印一次:
>>> a = "querty"
>>> a[::2]
'qet'
Slicing works like this:切片的工作方式如下:
[from start: from end: step]
So, in your case, you are looking to simply print every second, so you want to make use of your step
.因此,在您的情况下,您希望每秒简单地打印一次,因此您想利用您的step
。 So, simply slice leaving the start
and end
empty, since you want to position yourself at the beginning of the string and then simply go every second.因此,只需将start
和end
切为空,因为您想将自己定位在字符串的开头,然后每秒执行一次。 This is the reasoning behind using [::2]
这就是使用[::2]
背后的原因
Every second letter should start with index of 1 not 0. So, if your input is "qwerty", you output should be "wry".每隔一个字母应以索引 1 而非 0 开头。因此,如果您的输入是“qwerty”,则输出应该是“wry”。
Code below may be able to answer your question.下面的代码或许可以回答您的问题。
sentence = input("\nPlease enter a string : ")
print("Every second letter of the string " + sentence + " is ", end="")
for i in range(len(sentence)):
if i % 2 == 1:
print(sentence[i] + " ", end="")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.