如何在python中使用join将以下代码输出转换为一行。。目前对于两个字的输入,我得到两行输出

2024-09-30 06:26:49 发布

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

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()

Tags: thetextinformconvertstringmaindef
3条回答

您可以使用列表来放置所有单词,或者以不同的方式使用print()
示例:

print(word, end="\t")

这里我使用关键字参数end将其设置为'\t'(默认为'\n'

几点提示:

  • 将代码转换为“一行”并不能让它变得更好。你知道吗
  • 无需键入所有辅音,使用string模块,并使用set来实现O(1)查找复杂性。你知道吗
  • 使用格式化的字符串文字(python3.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)

只需编辑代码,就可以将结果作为空格分隔的单词返回。你知道吗

def cat_latin_word(text):
    constant = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"
    result = []
    for word in text.split():
        if word[0] in constant:
            word = (str(word)[-1:] + str(word)[:4] + "eeoow")
            result.append(word)
        else:
            word = (str(word) + "eeoow")
            result.append(word)

    return ' '.join(result)

def main():
    text = 'ankit jaiswal'
    print(cat_latin_word(text))

相关问题 更多 >

    热门问题