简体   繁体   中英

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

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

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. This adds 1 to i, so in the next loop it becomes 2 and so on. Since you didn't add to i, i's value remained 1 and so didn't print.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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