我有这段代码,可以将用户输入的术语输出到控制台
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]
输入可以像he, haha, ho ho, he he he
一样,
当x = he
,y = haha, ho ho
和z = he he he
"he" "haha" "ho ho" -"he he he"
有人知道一种将打印输出("he" "haha" "ho ho" -"he he he"
)分配给变量j
的方法吗?
说明编辑:打印输出中的双引号并不表示其为字符串。整个过程基本上是吸收用户输入,将其以,
作为分隔符,然后将""
添加到每个以"term"
结尾的单独术语的开头和结尾,最终被放到与Google类似的搜索引擎中
答案 0 :(得分:1)
尝试一下
>>> 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)
输出:
>>> print(var)
'he haha ho ho - he he he'
编辑1:
>>> " ".join('"{}"'.format(el) if el is not '-' else el for el in x+y+['-']+z)
'"he" "haha" " ho ho" - "he he he"'
答案 1 :(得分:0)
尝试一下:
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)
输出:
Input x: ha, ha
Input y: he, he, he
Input z: huh, hih
('"ha ha"', '"he he he"', '-"huh hih"')
答案 2 :(得分:0)
您正在尝试使用打印语句来帮助您设置字符串格式。如前所述,print()
将始终返回None
。相反,您可以按照以下方式格式化字符串:
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)
这将显示:
"he" "haha" "ho ho" -"he he he"
答案 3 :(得分:0)
我建议您先构造字符串然后再打印。
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 )
输出:
'"he" "haha" "ho ho" "he he he"'