Hoe kan ik variabele en string op dezelfde regel in Python afdrukken?

Ik gebruik python om te berekenen hoeveel kinderen er in 5 jaar zouden worden geboren als er elke 7 seconden een kind zou worden geboren. Het probleem zit in mijn laatste regel. Hoe zorg ik ervoor dat een variabele werkt als ik tekst aan weerszijden ervan afdruk?

Hier is mijn code:

currentPop = 312032486
oneYear = 365
hours = 24
minutes = 60
seconds = 60
# seconds in a single day
secondsInDay = hours * minutes * seconds
# seconds in a year
secondsInYear = secondsInDay * oneYear
fiveYears = secondsInYear * 5
#Seconds in 5 years
print fiveYears
# fiveYears in seconds, divided by 7 seconds
births = fiveYears // 7
print "If there was a birth every 7 seconds, there would be: " births "births"

Antwoord 1, autoriteit 100%

Gebruik ,om tekenreeksen en variabelen te scheiden tijdens het afdrukken:

print("If there was a birth every 7 seconds, there would be: ", births, "births")

,in de printfunctie scheidt de items door een enkele spatie:

>>> print("foo", "bar", "spam")
foo bar spam

of beter stringopmaak:

print("If there was a birth every 7 seconds, there would be: {} births".format(births))

String-opmaak is veel krachtiger en stelt je in staat om ook een aantal andere dingen te doen, zoals opvulling, opvulling, uitlijning, breedte, precisie instellen, enz.

>>> print("{:d} {:03d} {:>20f}".format(1, 2, 1.1))
1 002             1.100000
  ^^^
  0's padded to 2

Demo:

>>> births = 4
>>> print("If there was a birth every 7 seconds, there would be: ", births, "births")
If there was a birth every 7 seconds, there would be:  4 births
# formatting
>>> print("If there was a birth every 7 seconds, there would be: {} births".format(births))
If there was a birth every 7 seconds, there would be: 4 births

Antwoord 2, autoriteit 30%

Python is een zeer veelzijdige taal. U kunt variabelen op verschillende manieren afdrukken. Ik heb hieronder vijf methoden opgesomd. Je kunt ze gebruiken zoals het je uitkomt.

Voorbeeld:

a = 1
b = 'ball'

Methode 1:

print('I have %d %s' % (a, b))

Methode 2:

print('I have', a, b)

Methode 3:

print('I have {} {}'.format(a, b))

Methode 4:

print('I have ' + str(a) + ' ' + b)

Methode 5:

print(f'I have {a} {b}')

De uitvoer zou zijn:

I have 1 ball

Antwoord 3, autoriteit 20%

Nog twee

De eerste

>>> births = str(5)
>>> print("there are " + births + " births.")
there are 5 births.

Bij het toevoegen van strings, concateneren ze.

de tweede

Ook de format(Python 2.6 en nieuwere) methode van snaren is waarschijnlijk de standaardweg:

>>> births = str(5)
>>>
>>> print("there are {} births.".format(births))
there are 5 births.

Dit formatMethod kan ook met lijsten worden gebruikt

>>> format_list = ['five', 'three']
>>> # * unpacks the list:
>>> print("there are {} births and {} deaths".format(*format_list))  
there are five births and three deaths

of woordenboeken

>>> format_dictionary = {'births': 'five', 'deaths': 'three'}
>>> # ** unpacks the dictionary
>>> print("there are {births} births, and {deaths} deaths".format(**format_dictionary))
there are five births, and three deaths

Antwoord 4, Autoriteit 9%

Als u met Python 3 wilt werken, is het heel eenvoudig:

print("If there was a birth every 7 second, there would be %d births." % (births))

Antwoord 5, Autoriteit 6%

Vanaf Python 3.6 U kunt Literale reeksinterpolatie.

births = 5.25487
>>> print(f'If there was a birth every 7 seconds, there would be: {births:.2f} births')
If there was a birth every 7 seconds, there would be: 5.25 births

Antwoord 6, autoriteit 6%

U kunt de methoden f-stringof .format()gebruiken

F-string gebruiken

print(f'If there was a birth every 7 seconds, there would be: {births} births')

Gebruik .format()

print("If there was a birth every 7 seconds, there would be: {births} births".format(births=births))

Antwoord 7, autoriteit 4%

Je kunt een formatstring gebruiken:

print "There are %d births" % (births,)

of in dit eenvoudige geval:

print "There are ", births, "births"

Antwoord 8, autoriteit 2%

Als u python 3.6 of de nieuwste versie gebruikt,
f-string is de beste en makkelijke

print(f"{your_varaible_name}")

Antwoord 9

Je zou eerst een variabele maken: bijvoorbeeld: D = 1. Doe dit dan maar vervang de string door wat je maar wilt:

D = 1
print("Here is a number!:",D)

Antwoord 10

In een huidige python-versie moet je haakjes gebruiken, zoals:

print ("If there was a birth every 7 seconds", X)

Antwoord 11

Je kunt hiervoor string-opmaakgebruiken:

print "If there was a birth every 7 seconds, there would be: %d births" % births

of je kunt printmeerdere argumenten geven, en het zal ze automatisch scheiden door een spatie:

print "If there was a birth every 7 seconds, there would be:", births, "births"

Antwoord 12

gebruik String-opmaak

print("If there was a birth every 7 seconds, there would be: {} births".format(births))
 # Will replace "{}" with births

als je een speelgoedproject doet, gebruik dan:

print('If there was a birth every 7 seconds, there would be:' births'births) 

of

print('If there was a birth every 7 seconds, there would be: %d births' %(births))
# Will replace %d with births

Antwoord 13

Ik heb je script gekopieerd en geplakt in een .py-bestand. Ik heb het uitgevoerd zoals het is met Python 2.7.10 en kreeg dezelfde syntaxisfout. Ik heb ook het script in Python 3.5 geprobeerd en kreeg de volgende uitvoer:

File "print_strings_on_same_line.py", line 16
print fiveYears
              ^
SyntaxError: Missing parentheses in call to 'print'

Vervolgens heb ik de laatste regel waar het aantal geboorten wordt afgedrukt als volgt gewijzigd:

currentPop = 312032486
oneYear = 365
hours = 24
minutes = 60
seconds = 60
# seconds in a single day
secondsInDay = hours * minutes * seconds
# seconds in a year
secondsInYear = secondsInDay * oneYear
fiveYears = secondsInYear * 5
#Seconds in 5 years
print fiveYears
# fiveYears in seconds, divided by 7 seconds
births = fiveYears // 7
print "If there was a birth every 7 seconds, there would be: " + str(births) + " births"

De uitvoer was (Python 2.7.10):

157680000
If there was a birth every 7 seconds, there would be: 22525714 births

Ik hoop dat dit helpt.


Antwoord 14

Gebruik gewoon , (komma) ertussen.

Bekijk deze code voor een beter begrip:

# Weight converter pounds to kg
weight_lbs = input("Enter your weight in pounds: ")
weight_kg = 0.45 * int(weight_lbs)
print("You are ", weight_kg, " kg")

Antwoord 15

gebruik tekenreeksindeling:

birth = 5.25487
print(f'''
{birth} 
''')

Antwoord 16

Iets anders: Python 3 gebruiken en verschillendevariabelen op dezelfde regel afdrukken:

print("~~Create new DB:",argv[5],"; with user:",argv[3],"; and Password:",argv[4]," ~~")

Antwoord 17

PYTHON 3

Het is beter om de formaatoptie te gebruiken

user_name=input("Enter your name : )
points = 10
print ("Hello, {} your point is {} : ".format(user_name,points)

of declareer de invoer als string en gebruik

user_name=str(input("Enter your name : ))
points = 10
print("Hello, "+user_name+" your point is " +str(points))

Antwoord 18

Als je een komma gebruikt tussen de tekenreeksen en de variabele, zoals dit:

print "If there was a birth every 7 seconds, there would be: ", births, "births"

Other episodes