1

I am trying to apply for loop in the print statement in Python 3.7.

For example

string1="Liverpool is always alone"
string2="Manchester United is the best team in the world"
string3="Tottenham Hotspur is for losers"
string4="Leicester City is overrated"

for i in range(1,5):
    print(string%i.find(" is"))  # <---this is the problem

My ultimate aim is to get

9
17
17
14

Sure, I can store the results in a list and then print the results like this:

 results=[string1.find(" is"),
          string2.find(" is"),
          string3.find(" is"),
          string4.find(" is")]

    for i in range(1,4):
        print(results[i])

But it will be troublesome especially when the number of string becomes too much.

Please suggest a way to print the multiple strings using for loop.

I'm using Python 3.7.

3
  • 4
    I would contest that declaring variables string1, string2, ... is more troublesome than storing all the strings in a list called strings (without declaring the variables). If you store all of them in a list, you can simply have for string in strings: print string.find(' is') Commented Nov 28, 2018 at 3:34
  • 1
    btw range(1,4) will iterate on 1,2,3 only Commented Nov 28, 2018 at 3:36
  • @slider fair point. Have my upvote Commented Nov 28, 2018 at 5:20

1 Answer 1

6

Put the strings in a list:

statements = [
    "Liverpool is always alone",
    "Manchester United is the best team in the world",
    "Tottenham Hotspur is for losers",
    "Leicester City is overrated",
]

Then you can easily loop over them:

for s in statements:
    print(s.find(" is"))
Sign up to request clarification or add additional context in comments.

2 Comments

I agree about the list, then just [print(s.find(" is")) for s in statements] to print
alright, I guess this is the closest I can ever get to concatenate integer with variable name in the print statement

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.