Home > Mobile >  How to print strings and integers in the same line?
How to print strings and integers in the same line?

Time:04-28

I'm trying to print each item in the following two lists:

lNames = ['John','David','Michael']
lAges = [45,14,32] 

with the format: "Person 0, Name: John, Age 34".

I tried adding another list:

```py
lPersons = [0, 1, 2] 

Tried this code:

lNames = ['John','David','Michael']
lAges = [45,14,32]
lPersons = [0, 1, 2]

for a in lNames:
    for b in lAges:
        for c in lPersons:
            print("Person: "   c   ", Name: "   a   ", Age: "   b)

This gave a TypeError, because I'm incorrectly combining integers with strings when printing. What am I missing for the desired outcome?

CodePudding user response:

Two issues:

  1. There's more nesting in the for loops than necessary. You don't want to iterate over each combination of elements from all three lists; rather, you have a list of people and information about those people, and you want to print their information out one person at a time. This only requires one pass through each list.

  2. You can't concatenate a string and an integer, as the error states. You can use an f-string instead.

Here is a code snippet that resolves both issues:

for i in range(len(lNames)):
    print(f"Person: {lPersons[i]}, Name: {lNames[i]}, Age: {lAges[i]}")

Or, even better, use zip():

for name, age, person_id in zip(lNames, lAges, lPersons):
    print(f"Person: {person_id}, Name: {name}, Age: {age}")

These output:

Person: 0, Name: John, Age: 45
Person: 1, Name: David, Age: 14
Person: 2, Name: Michael, Age: 32

CodePudding user response:

Providing that your names and ages lists are of the same length then you could do this:

names = ['John','David','Michael']
ages = [45,14,32]

for i, (n, a) in enumerate(zip(names, ages)):
    print(f'Person {i}, Name: {n}, Age {a}')

Output:

Person 0, Name: John, Age 45
Person 1, Name: David, Age 14
Person 2, Name: Michael, Age 32

CodePudding user response:

Without using f"" formatting, you can use one single for loop to achieve that result, but you will need to check before proceeding with that solution that your three lists have the same length and their data is correct:

lNames = ['John','David','Michael']
lAges = [45,14,32]

for i in range(len(lAges)):
    print("Person: "   str(i)   ", Name: "   lNames[i]   ", Age: "   str(lAges[i]))
  • Related