【问题标题】:is there any simple way to do this than what i did有什么比我做的更简单的方法吗
【发布时间】:2020-12-29 07:33:42
【问题描述】:

让我们创建一个将文本转换为猪拉丁语的函数:一个简单的文本转换,它修改每个单词,将第一个字符移到末尾,并将“ay”附加到末尾。例如,python 以 ythonpay 结尾。

 def pig_latin(text):
    list=[]
    string=""
    # Separate the text into words
    for word in text.split():
        list.append(word[1:]+word[0]+"ay")
    # Create the pig latin word and add it to the list
    # Turn the list back into a phrase
    for n in list:
        string = string + n +" "
    return string.rstrip()

print(pig_latin("hello how are you")) # Should be "ellohay owhay reaay ouyay"
print(pig_latin("programming in python is fun")) # Should be "rogrammingpay niay ythonpay siay unfay"

【问题讨论】:

    标签: python string list methods append


    【解决方案1】:

    您可以尝试列表理解:

    >>> pig_latin = lambda s: ' '.join([i[1:] + i[0] + 'ay' for i in s.split(' ')])
    
    >>> pig_latin("hello how are you")
    'ellohay owhay reaay ouyay'
    
    >>> pig_latin("programming in python is fun")
    'rogrammingpay niay ythonpay siay unfay'
    

    【讨论】:

    • 它很棒,但我不知道该怎么做,谢谢
    • @NELSONJOSEPH 这有什么问题?
    • 一个改变字符串格式的函数
    【解决方案2】:

    你可以试试这个:

    def pig_latin(text):
        list = []
        for word in text.split():
            list.append(word[1:] + word[0] + "ay")
    
        return " ".join(list)
    
    print(pig_latin("hello how are you"))
    print(pig_latin("programming in python is fun"))
    

    【讨论】:

    • 非常感谢,我一直在寻找一种更简单的方法来使列表更容易串起来,尽管我研究了连接方法,但我从未使用过
    【解决方案3】:
    text = "hello how are you"
    for word in text.split():
        latin = word[1:] + word[:1] + 'ay'
        print(latin)
    

    结果:

    ['hello', 'how', 'are', 'you']
    ellohay
    owhay
    reaay
    ouyay
    

    在你上面的函数中实现这个

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-21
      • 1970-01-01
      • 1970-01-01
      • 2011-08-16
      • 2011-09-15
      • 1970-01-01
      相关资源
      最近更新 更多