gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:03:42 28 4
gpt4 key购买 nike

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

最佳答案

一些提示:

  • 将代码转换为“一行”并不会使其变得更好。
  • 无需输入所有辅音,使用 string 模块并使用 set 实现 O(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)

关于python - 如何使用 python 中的 join 将以下代码输出转换为一行。目前,对于两个单词输入,我得到两行输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52254377/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com