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?

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

it should print "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"

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. 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. This is the reasoning behind using [::2]

网友答案:

Every second letter should start with index of 1 not 0. So, if your input is "qwerty", you output should be "wry".