使用u str_uu返回可变数量的不同行字符串?

2024-04-25 06:56:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个用python3.x创建“Facebook”的项目,我目前所做的是使用str函数返回不同行上的字符串。在

我使用的代码是:

class Status:
    likers = []
    commentObjs = []
    def __init__(self, statusPoster, statusMsg, likers, commentObjs):
        self.statuser = statusPoster
        self.status = statusMsg
        self.likers = likers
        self.commentObjs = commentObjs

以及

^{pr2}$

我遇到的问题是likers的数量和commentobj的数量是可变的。在

如果只有一个值,例如:

likers = ["Spongebob"] 
commentObjs = ["Spongebob: You should watch the Spongebob movie!"]

它在终端返回:

Brad Pitt will watch a movie today!
Spongebob likes this.
Spongebob: You should watch The Spongebob movie!

但如果每个列表中有多个值,例如:

likers = ["Spongebob","Harry Potter"] 
commentObjs = ["Spongebob: You should watch the Spongebob movie!","Brad Pitt: How about nah?"]

它返回:

Brad Pitt will watch a movie today!
Spongebob, Harry Potter likes this.
Spongebob: You should watch The Spongebob movie!
Brad Pitt: Nah, I will probably watch Mr and Mrs. Smith.

我能想到的唯一可能的方法是使用for循环和len(likers),但我不知道如何在返回名称和状态的常量值的同时做到这一点。在


Tags: theselfyou数量moviewillwatchshould
1条回答
网友
1楼 · 发布于 2024-04-25 06:56:40

你在这里找^{}。这允许您使用连接字符串连接多个字符串(可以为空):

>>> likers = ['Spongebob', 'Harry Potter']
>>> ', '.join(likers)
'Spongebob, Harry Potter'
>>> ' -> '.join(likers)
'Spongebob -> Harry Potter'

您可能还想了解^{}如何将值插值到模板字符串中:

^{pr2}$

这将用逗号连接您的likers值,并用换行符将注释连接起来。在

您不应该将其用作您的__repr__;这样会产生调试输出,从而帮助您区分类的两个实例,可以选择使用输出中包含的值部分。在

相关问题 更多 >

    热门问题