我正在编写一个程序,将列表和数字中的字符串连接在一起,但是我无法摆脱字符串周围的引号。我需要在字符串,y坐标和半径之后使用分号,但在分号之后不需要逗号。这可能吗? 我希望格式如下:
Circle; 80, 72; 15; 32, 208, 86
我尝试了单个分号并删除了逗号,但它不起作用
from random import randrange
from random import choice
def randomShape():
x = randrange (0,400)
y = randrange (0,400)
radius = randrange (0,100)
red = randrange (192, 208)
blue =randrange(100,140)
green =randrange(150,175)
shape = ['square;' , 'rectangle;']
randomShape = choice (shape)
JoinList =(randomShape,x,y,radius,red,blue,green)
print(JoinList)
def main():
randomShape()
main()
答案 0 :(得分:0)
您说过要创建一个字符串,但输出是一个列表。 您可以通过简单地使用带占位符的字符串模式作为变量来实现此结果。您可以为此使用f-strings。我已将此代码放入一个单独的函数中以摆脱混乱:
def join_shape_data(shape, x, y, radius, red, blue, green):
return f"{shape} {x}, {y}; {radius}; {red}, {blue}, {green}"
因此您可以在randomShape()函数中调用它,这将生成您想要的东西。
答案 1 :(得分:0)
如果您的问题只是按照所述格式打印,请替换打印语句,如下所示:
import tensorflow as tf
def test_1():
G = tf.Graph()
with G.as_default():
x = tf.get_variable('x', initializer=1)
with tf.Session() as sess:
sess.run(tf.initializers.global_variables())
print(sess.run(x))
print(4 / 0)
def test_2():
G = tf.Graph()
with G.as_default():
x = tf.get_variable('x', initializer=1)
with tf.Session() as sess:
sess.run(tf.initializers.global_variables())
print(sess.run(x))
输出:
print(randomShape,x,",",y,";",radius,";",red,",",blue,",",green)
这应该解决。
答案 2 :(得分:0)
定义变量:
In [83]: randomShape,x,y,radius,red,blue,green = 'Circle', 80, 72, 15, 32, 208, 86
使用经典的%Python样式设置字符串格式:
In [84]: '%s; %d, %d; %d; %d, %d, %d'%(randomShape,x,y,radius,red,blue,green)
Out[84]: 'Circle; 80, 72; 15; 32, 208, 86'
,如果我们在字符串中输入print
:
In [85]: print(_)
Circle; 80, 72; 15; 32, 208, 86
或使用更新的format
样式:
In [88]: '{}; {}, {}; {}; {}, {}, {}'.format(randomShape,x,y,radius,red,blue,green)
Out[88]: 'Circle; 80, 72; 15; 32, 208, 86'
已经提到了较新的'f'字符串变体:
In [90]: f'{randomShape}; {x}, {y}; {radius}; {red}, {blue}, {green}'
Out[90]: 'Circle; 80, 72; 15; 32, 208, 86'