¿Cómo puedo imprimir variables y cadenas en la misma línea en Python?

176

Estoy usando python para calcular cuántos niños nacerían en 5 años si un niño naciera cada 7 segundos. El problema está en mi última línea. ¿Cómo hago que una variable funcione cuando imprimo texto a cada lado?

Aquí está mi código:

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"
Bob Uni
fuente
Tenga cuidado en 2020 (sentido común, lo sé: D). Imprimir se ha convertido en una función en Python3, necesita ser usado con corchetes ahora: print(something)(También Python2 está desactualizado desde este año.)
PythoNic

Respuestas:

262

Use ,para separar cadenas y variables mientras imprime:

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

, en la declaración impresa separa los elementos por un solo espacio:

>>> print "foo","bar","spam"
foo bar spam

o mejor usar el formato de cadena :

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

El formateo de cadenas es mucho más potente y le permite hacer otras cosas, como: relleno, relleno, alineación, ancho, ajuste de precisión, etc.

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

Manifestación:

>>> 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
Ashwini Chaudhary
fuente
Ninguno de estos funciona en Pyton 3. Por favor, vota la respuesta de Gagan Agrawal.
Axel Bregnsbo
58

dos más

El primero

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

Al agregar cadenas, se concatenan.

El segundo

También el formatmétodo de cadenas (Python 2.6 y más reciente) es probablemente la forma estándar:

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

Este formatmétodo también se puede usar con listas

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

o diccionarios

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

Python es un lenguaje muy versátil. Puede imprimir variables por diferentes métodos. He enumerado a continuación 4 métodos. Puede usarlos según su conveniencia.

Ejemplo:

a=1
b='ball'

Método 1:

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

Método 2:

print('I have',a,b)

Método 3:

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

Método 4:

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

Método 5:

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

La salida sería:

I have 1 ball
Gagan Agrawal
fuente
La decisión está relacionada con su estilo de programación: M2 es programación procesal, M3 es programación orientada a objetos. La palabra clave para M5 tiene formato literal de cadena . Las operaciones de cadena como M1 y M4 deben usarse si es necesario, lo que no es el caso aquí (M1 para diccionarios y tuplas; M4, por ejemplo, para arte ascii-art y otros resultados formateados)
PythoNic
29

Si quieres trabajar con Python 3, es muy simple:

print("If there was a birth every 7 second, there would be %d births." % (births))
Entrenador de codificación de Python
fuente
16

A partir de python 3.6, puede usar la interpolación de cadenas literales.

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
PabTorre
fuente
1
Mi favorito para cuerdas complejas.
Jason LeMonier
14

Puede usar los métodos f-string o .format ()

Usando f-string

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

Usando .format ()

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

Puede usar una cadena de formato:

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

o en este simple caso:

print "There are ", births, "births"
enpenax
fuente
2
tenga cuidado si usa esa segunda forma, porque eso es una tupla, no una cadena.
TehTris
5

Si está utilizando Python 3.6 o más reciente, f-string es el mejor y más fácil.

print(f"{your_varaible_name}")
Csmasterme
fuente
3

Primero haría una variable: por ejemplo: D = 1. Luego haga esto pero reemplace la cadena con lo que quiera:

D = 1
print("Here is a number!:",D)
Programación de Pythonbites
fuente
3

En una versión actual de Python, debe usar paréntesis, así:

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

usar formato de cadena

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

si estás haciendo un proyecto de juguete usa:

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

o

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

Puede usar el formato de cadena para hacer esto:

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

o puede dar printmúltiples argumentos, y los separará automáticamente por un espacio:

print "If there was a birth every 7 seconds, there would be:", births, "births"
Ámbar
fuente
gracias por la respuesta Amber. ¿Puedes explicar qué hace la 'd' después del símbolo%? gracias
Bob Uni
2
%dsignifica "formatear el valor como un entero". Del mismo modo, %ssería "valor de formato como una cadena" y %fes "valor de formato como un número de coma flotante". Estos y más están documentados en la parte del manual de Python a la que he vinculado en mi respuesta.
Ámbar
1

Copié y pegué tu script en un archivo .py. Lo ejecuté tal cual con Python 2.7.10 y recibí el mismo error de sintaxis. También probé el script en Python 3.5 y recibí el siguiente resultado:

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

Luego, modifiqué la última línea donde imprime el número de nacimientos de la siguiente manera:

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"

El resultado fue (Python 2.7.10):

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

Espero que esto ayude.

Debug255
fuente
1

Solo use, (coma) en el medio.

Vea este código para una mejor comprensión:

# 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")
Faisal Ahmed
fuente
0

Ligeramente diferente: Usando Python 3 e imprime varias variables en la misma línea:

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

PITÓN 3

Mejor usar la opción de formato

user_name=input("Enter your name : )

points = 10

print ("Hello, {} your point is {} : ".format(user_name,points)

o declarar la entrada como cadena y usar

user_name=str(input("Enter your name : ))

points = 10

print("Hello, "+user_name+" your point is " +str(points))
Bromount
fuente
1
String "Enter your name :falla entre comillas de cierre
barbsan
print ("Hello, {} your point is {} : ".format(user_name,points) Falta el soporte de cierre.
Hillsie
0

Si usa una coma entre las cadenas y la variable, así:

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

fuente