Druk meerdere argumenten af in Python

Dit is slechts een fragment van mijn code:

print("Total score for %s is %s  ", name, score)

Maar ik wil dat het wordt afgedrukt:

“Totale score voor (naam) is (score)”

waarbij nameeen variabele in een lijst is en scoreeen geheel getal is. Dit is Python 3.3 als dat al helpt.


Antwoord 1, autoriteit 100%

Er zijn veel manieren om dit te doen. Om je huidige code te corrigeren met behulp van %-formattering, moet je een tuple invoeren:

  1. Geef het door als een tuple:

    print("Total score for %s is %s" % (name, score))
    

Een tuple met een enkel element ziet eruit als ('this',).

Hier zijn enkele andere veelvoorkomende manieren om dit te doen:

  1. Geef het door als een woordenboek:

    print("Total score for %(n)s is %(s)s" % {'n': name, 's': score})
    

Er is ook een nieuwe tekenreeksopmaak, die misschien wat gemakkelijker te lezen is:

  1. Gebruik tekenreeksopmaak in nieuwe stijl:

    print("Total score for {} is {}".format(name, score))
    
  2. Gebruik tekenreeksopmaak in nieuwe stijl met getallen (handig voor het opnieuw ordenen of afdrukken van dezelfde reeks):

    print("Total score for {0} is {1}".format(name, score))
    
  3. Gebruik tekenreeksopmaak in nieuwe stijl met expliciete namen:

    print("Total score for {n} is {s}".format(n=name, s=score))
    
  4. Samenvoegen van tekenreeksen:

    print("Total score for " + str(name) + " is " + str(score))
    

De duidelijkste twee, naar mijn mening:

  1. Geef de waarden gewoon door als parameters:

    print("Total score for", name, "is", score)
    

    Als u niet wilt dat spaties automatisch worden ingevoegd door printin het bovenstaande voorbeeld, wijzigt u de parameter sep:

    print("Total score for ", name, " is ", score, sep='')
    

    Als je Python 2 gebruikt, kun je de laatste twee niet gebruiken omdat printgeen functie is in Python 2. Je kunt dit gedrag echter wel importeren vanuit __future__:

    from __future__ import print_function
    
  2. Gebruik de nieuwe f-string opmaak in Python 3.6:

    print(f'Total score for {name} is {score}')
    

Antwoord 2, autoriteit 10%

Er zijn veel manieren om dat af te drukken.

Laten we eens kijken met een ander voorbeeld.

a = 10
b = 20
c = a + b
#Normal string concatenation
print("sum of", a , "and" , b , "is" , c) 
#convert variable into str
print("sum of " + str(a) + " and " + str(b) + " is " + str(c)) 
# if you want to print in tuple way
print("Sum of %s and %s is %s: " %(a,b,c))  
#New style string formatting
print("sum of {} and {} is {}".format(a,b,c)) 
#in case you want to use repr()
print("sum of " + repr(a) + " and " + repr(b) + " is " + repr(c))
EDIT :
#New f-string formatting from Python 3.6:
print(f'Sum of {a} and {b} is {c}')

Antwoord 3, Autoriteit 8%

Gebruik: .format():

print("Total score for {0} is {1}".format(name, score))

of:

// Recommended, more readable code
print("Total score for {n} is {s}".format(n=name, s=score))

of:

print("Total score for" + name + " is " + score)

of:

print("Total score for %s is %d" % (name, score))

of: f-stringFormatteren van Python 3.6 :

print(f'Total score for {name} is {score}')

Kan reprgebruiken en automatisch de ''wordt toegevoegd:

print("Total score for" + repr(name) + " is " + repr(score))
# or for advanced: 
print(f'Total score for {name!r} is {score!r}') 

Antwoord 4, Autoriteit 4%

In Python 3.6, f-stringis veel schoner.

In eerdere versie:

print("Total score for %s is %s. " % (name, score))

in Python 3.6:

print(f'Total score for {name} is {score}.')

zal doen.

Het is efficiënter en eleganter.


Antwoord 5, autoriteit 2%

Om het simpel te houden, houd ik persoonlijk van stringsamenvoeging:

print("Total score for " + name + " is " + score)

Het werkt met zowel Python 2.7 als 3.X.

OPMERKING: als de score een intis, moet u deze converteren naar str:

print("Total score for " + name + " is " + str(score))

Antwoord 6, autoriteit 2%

Volg dit gewoon

grade = "the biggest idiot"
year = 22
print("I have been {} for {} years.".format(grade, year))

OF

grade = "the biggest idiot"
year = 22
print("I have been %s for %s years." % (grade, year))

En vergeet alle andere, anders kunnen de hersenen niet alle formaten in kaart brengen.


Antwoord 7, autoriteit 2%

Probeer het gewoon:

print("Total score for", name, "is", score)

Antwoord 8

print("Total score for %s is %s  " % (name, score))

%skan worden vervangen door %dof %f


Antwoord 9

Gebruik f-string:

print(f'Total score for {name} is {score}')

Of

Gebruik .format:

print("Total score for {} is {}".format(name, score))

Antwoord 10

Als scoreeen getal is, dan

print("Total score for %s is %d" % (name, score))

Als score een tekenreeks is, dan

print("Total score for %s is %s" % (name, score))

Als score een getal is, dan is het %d, als het een string is, dan is het %s, als score een float is, dan is het %f


Antwoord 11

Dit is wat ik doe:

print("Total score for " + name + " is " + score)

Vergeet niet om een spatie te plaatsen na foren voor en na is.


Antwoord 12

Dit was waarschijnlijk een casting issue. Casting syntaxgebeurt wanneer u twee verschillende types of variablesprobeert te combineren. Aangezien we een stringniet altijd kunnen converteren naar een integerof float, moeten we onze integersconverteren naar een string. Dit is hoe je het doet.: str(x). Om te converteren naar een geheel getal is dit: int(x), en een float is float(x). Onze code is:

print('Total score for ' + str(name) + ' is ' + str(score))

Ook! Voer dit snippetuit om een tabel te zien met hoe u verschillende types of variableskunt converteren!

<table style="border-collapse: collapse; width: 100%;background-color:maroon; color: #00b2b2;">
<tbody>
<tr>
<td style="width: 50%;font-family: serif; padding: 3px;">Booleans</td>
<td style="width: 50%;font-family: serif; padding: 3px;"><code>bool()</code></td>
  </tr>
 <tr>
<td style="width: 50%;font-family: serif;padding: 3px">Dictionaries</td>
<td style="width: 50%;font-family: serif;padding: 3px"><code>dict()</code></td>
</tr>
<tr>
<td style="width: 50%;font-family: serif;padding: 3px">Floats</td>
<td style="width: 50%;font-family: serif;padding: 3px"><code>float()</code></td>
</tr>
<tr>
<td style="width: 50%;font-family: serif;padding:3px">Integers</td>
<td style="width: 50%;font-family: serif;padding:3px;"><code>int()</code></td>
</tr>
<tr>
<td style="width: 50%;font-family: serif;padding: 3px">Lists</td>
<td style="width: 50%font-family: serif;padding: 3px;"><code>list()</code></td>
</tr>
</tbody>
</table>

Other episodes