首页 > 解决方案 > 如何在 python 中使用 join 将以下代码输出转换为一行。目前对于两个单词输入,我在两行中得到输出

问题描述

def cat_latin_word(text):
    """ convert the string in another form
    """

    constant = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"

    for word in text.split():
        if word[0] in constant:
            word = (str(word)[-1:] + str(word)[:4] + "eeoow")
        else:
            word = (str(word) + "eeoow")
        print(word)



def main():
    """ converts"""
    text = input("Enter a sentence ")
    cat_latin_word(text)

main()

标签: pythonstring

解决方案


几点建议:

  • 将您的代码转换为“一行”并不能让它变得更好。
  • 无需输入所有辅音,使用string模块并使用setO(1) 查找复杂度。
  • 使用格式化的字符串文字(Python 3.6+)以获得更易读和更高效的代码。
  • 无需对str已经是字符串的变量使用。
  • 对于单行,您可以将列表推导与三元语句和' '.join.

这是一个工作示例:

from string import ascii_lowercase, ascii_uppercase

def cat_latin_word(text):

    consonants = (set(ascii_lowercase) | set(ascii_uppercase)) - set('aeiouAEIOU')

    print(' '.join([f'{word}eeow' if not word[0] in consonants else \
                    f'{word[-1:]}{word[:4]}eeoow' for word in text.split()]))

text = input("Enter a sentence ")
cat_latin_word(text)

推荐阅读