简体   繁体   English

将元组的每个元素拆分成新行

[英]Split each element of tuple into new line

I have a problem to split each element of tuple into new line.我在将元组的每个元素拆分为新行时遇到问题。

I have to define my own class Songs and I have to use into this class _ _ init _ _ which should contain arguments: self, lyrics.我必须定义我自己的类 Songs 并且我必须在这个类中使用 _ _ init _ _ ,它应该包含参数:self,歌词。 Into that class I have to create method sing_me which is going to split every element of tuple into new lines.在那个类中,我必须创建方法 sing_me,它将把元组的每个元素拆分成新行。

I have to contain this line in main function:我必须在主函数中包含这一行:

Let_go = Songs(['When it"s black, ', 'Take a little time to hold yourself, ', 'Take a little time to feel around, ', 'Before it"s gone!']).

I have really no idea how can I do this without converting that tuple into string but I can't really do it :/.我真的不知道如何在不将该元组转换为字符串的情况下做到这一点,但我真的做不到:/。

Do you have any solutions how can I do it?你有什么解决方案我该怎么做?

Here's my code in which I'm stuck:这是我卡在其中的代码:

class Songs:
    def __init__(self, lyrics):
        self.lyrics = lyrics
    def sing_me:
        # don't know here what should I do

def main():
    Let_go = Songs(['When it"s black, ', 'Take a little time to hold yourself, ', 'Take a little time to feel around, ', 'Before it"s gone!'])

Output should look like: When it"s black,输出应该是这样的:当它是黑色时,

Take a little time to hold yourself,给自己一点时间,
Take a little time to feel around,花点时间感受一下,
Before it"s gone!在它消失之前!

It seems like a course exercice so you should search a little more by yourself.这似乎是一个课程练习,所以你应该自己多搜索一点。

Without giving you the code, an idea could be to loop over the class attribute lyrics and print each element.在不提供代码的情况下,一个想法可能是循环遍历类属性歌词并打印每个元素。

Be careful your definition of your method sing_me is incorrect.请注意您对方法sing_me定义不正确。

To split the tuple with newlines, you need to call the "\\n".join() function.要使用换行符拆分元组,您需要调用"\\n".join()函数。 However, you need to first convert all of the elements in the tuple into strings.但是,您需要先将元组中的所有元素都转换为字符串。

The following expression should work on a given tuple:以下表达式应该适用于给定的元组:

"\n".join(str(el) for el in mytuple)

Note that this is different from converting the entire tuple into a string.请注意,这与将整个元组转换为字符串不同。 Instead, it iterates over the tuple and converts each element into its own string.相反,它遍历元组并将每个元素转换为它自己的字符串。

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

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