w4tchdoge
w4tchdoge

Reputation: 13

Assign the output of a print function to variable

I've got this code which outputs a print of user inputted terms to console

x = input("Input x: ")
y = input("Input y: ")
z = input("Input z: ")

xS = x.split(", ")
yS = y.split(", ")
zS = z.split(", ")

[print('"{}"'.format(i), end=" ") for i in xS] + [print('"{}"'.format(i), end=" ") for i in yS] + [print('-"{}"'.format(i), end=" ") for i in zS]

where the inputs can be like he, haha, ho ho, he he he, and the print function outputs like so when x = he, y = haha, ho ho, and z = he he he

"he" "haha" "ho ho" -"he he he"

Does anyone know a way to assign the output of the print ("he" "haha" "ho ho" -"he he he") to a variable like j?

CLARIFICATION EDIT: the double quotes in the print output aren't saying that its a string. This whole thing is basically taking in user input, splitting it up with , as a delimiter, and adding the "" to the start and end of each separated term which end up as "term", that finally gets put into a search engine that works similar to Google's

Upvotes: 1

Views: 134

Answers (4)

shaik moeed
shaik moeed

Reputation: 5785

Try this,

>>> x = ['he'];y = 'haha, ho ho'.split(',');z = ['he he he']  
>>> x+y+['-']+z  
['he', 'haha', ' ho ho', '-', 'he he he']
>>> var = " ".join(x+y+['-']+z)

Output:

>>> print(var)    
'he haha  ho ho - he he he'

Edit 1:

>>> " ".join('"{}"'.format(el) if el is not '-' else el for el in x+y+['-']+z)        
'"he" "haha" " ho ho" - "he he he"'

Upvotes: 1

Stefan
Stefan

Reputation: 766

I recommend constructing the string yourself then printing it.

xS = "he"
yS = "haha, ho ho"
zS = "he he he"

j = " ".join( [ '"' + x.strip() + '"' for y in [xS,yS,zS] for x in y.split(',') ] )

print( j )

Output:

'"he" "haha" "ho ho" "he he he"'

Upvotes: 0

Oleg Vorobiov
Oleg Vorobiov

Reputation: 512

Try this:

x = input("Input x: ")
y = input("Input y: ")
z = input("Input z: ")

xS = x.split(", ")
yS = y.split(", ")
zS = z.split(", ")
j = ('"{}"'.format(' '.join(xS)), '"{}"'.format(' '.join(yS)), '-"{}"'.format(' '.join(zS)))

print (j)

output:

Input x: ha, ha
Input y: he, he, he
Input z: huh, hih
('"ha ha"', '"he he he"', '-"huh hih"')

Upvotes: 0

Martin Evans
Martin Evans

Reputation: 46759

You are trying to use a print statement to help with your string formatting. As noted, print() will always return None. You could instead just format your strings as follows:

x = "he"
y = "haha, ho ho" 
z = "he he he"

xS = x.split(", ")
yS = y.split(", ")
zS = z.split(", ")

j = ' '.join([f'"{i}"' for i in xS] + [f'"{i}"' for i in yS] + [f'-"{i}"' for i in zS])

print(j)

This would display:

"he" "haha" "ho ho" -"he he he"

Upvotes: 0

Related Questions