Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print strings and integers in the same line?

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?

like image 577
slb Avatar asked Dec 30 '25 16:12

slb


1 Answers

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
like image 117
BrokenBenchmark Avatar answered Jan 01 '26 04:01

BrokenBenchmark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!