简体   繁体   English

如何每两行字符串打印一行?

[英]How to print one line every two lines of a string?

Here is what I've tried:这是我尝试过的:

i = 1
text = str(input())
for i in range(nbLignes):
   if i % 2 != 0:
      print(text)

I couldn't find any answer else where我在其他地方找不到任何答案

if you have some text (with new lines) you can print every second line by splitting the str by lines and then use index slicing to pick only every second line starting from index 1如果您有一些文本(带有新行),您可以通过逐行拆分 str 来打印每一行,然后使用索引切片从索引 1 开始每隔一行选择一次

text = """line 1
line 2
line 3
line 4
line 5
line 6
line 7"""


for line in text.splitlines()[1::2]:
    print(line)

OUTPUT OUTPUT

line 2
line 4
line 6

If I understand correctly, you want to print the input every every other time in the range.如果我理解正确,您希望在该范围内每隔一段时间打印一次输入。 If so, then most of your code is correct.如果是这样,那么您的大部分代码都是正确的。 Add just one line:只添加一行:

i += 1

after the if statement.在 if 语句之后。 This adds 1 to i, so in the next loop it becomes 2 and so on.这将 1 添加到 i,因此在下一个循环中它变为 2,依此类推。 Since you didn't add to i, i's value remained 1 and so didn't print.由于您没有添加到 i,因此 i 的值保持为 1,因此没有打印。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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