python - 如何在 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()
解决方案
几点建议:
- 将您的代码转换为“一行”并不能让它变得更好。
- 无需输入所有辅音,使用
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)
推荐阅读
- ushort - 打开大文件并将其变成 ushort ?现有代码问题
- javascript - 使用 Dicer 将异步数据部分排序到文件中
- snowflake-cloud-data-platform - 找不到用户定义的函数
- google-apps-script - 如何以编程方式在 Google 文档中的特定位置添加表格?
- html - 如何使小 div 上的边框半径与大 div 相同
- powerbi - 计算 Power BI 中每个日期的不同 ID
- ckan - CKAN2.9 向数据集(包)表单添加上传字段
- python - expiringdict,在到期前打印
- c - 从动态库调用函数?
- keyboard - 自定义内置背光笔记本电脑键盘