简体   繁体   English

编写程序将输入的一行读取为字符串并在 Python 中打印字符串的每个第二个字母

[英]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.因此,只需将startend切为空,因为您想将自己定位在字符串的开头,然后每秒执行一次。 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.

相关问题 如何用大写和小写字母打印每个 8 个字母的字符串? (在蟒蛇中) - How to print every 8-letter string with uppercase and lowercase letters? (In python) Python-在每一行中写一个字符串 - Python - Write a string in every new line 编写一个程序,该程序接受用户输入的字符串并输出第二个单词 - Write a program that takes a user input string and outputs every second word 如何打印 python 中每个字符串的第一个字母、第二个字母和第三个字母? - How do I print the first letter and second letter and third.. of each string in python? 如何在 python 中编写一个程序,在不使用内置函数的情况下打印输入字符串的每个单词的第一个字母? - How to write a program in python which prints the fist letter of every word of the input string without using built-in fuctions? 读取每隔一行并打印到新文件 - Read every second line and print to new file 如何在python 3中编写每一行? - How to write every second line in python 3? 在 Python 中使用 index() 以外的方法将字符串中的每个第二个字母设为大写? - Making every second letter in a string uppercase with a method other than index() in Python? 在字符串中每隔一个字母插入一个值 -python - inserting a value every other letter in a string -python python读取文件,打印以特定字符串开头的行的一部分 - python read file, print part of line that begins with a specific string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM