首页 > 解决方案 > Python 字符串分隔符

问题描述

我正在编写一个程序来将列表和数字中的字符串连接在一起,但我无法摆脱字符串周围的引号。我需要字符串后的分号、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()

标签: pythonshapes

解决方案


你说你想创建一个字符串,但你的输出是一个列表。您可以通过简单地使用带有占位符的字符串模式来实现此结果。您可以为此使用f 字符串。我已将此代码放入单独的函数中以消除混乱:

def join_shape_data(shape, x, y, radius, red, blue, green):
    return f"{shape} {x}, {y}; {radius}; {red}, {blue}, {green}"

所以你可以在你的 randomShape() 函数中调用它,这将生成你想要的。


推荐阅读