简体   繁体   English

将打印函数的输出分配给变量

[英]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 ,当x = he , y = haha, ho hoz = 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 ?有谁知道将打印输出( "he" "haha" "ho ho" -"he he he" )分配给像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这整个事情基本上是接收用户输入,将其拆分为,作为分隔符,并将""添加到每个分隔的术语的开头和结尾,最终作为"term" ,最终被放入搜索引擎中工作原理类似于谷歌的

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:编辑1:

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

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"')

You are trying to use a print statement to help with your string formatting.您正在尝试使用打印语句来帮助您设置字符串格式。 As noted, print() will always return None .如前所述, print()将始终返回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"

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"'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM