You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python鹦鹉翻译器split后输出格式不符合预期问题求助

Fixing the Formatting Issue in Your Parrot Translator

Hey there! I see exactly what's going on with your code—right now, every time you print a translated word, it's getting its own line instead of staying in a single sentence like the original input. Let's fix that quickly.

The Problem

Your current loop uses print(words + "pa") inside each iteration, and each print() call adds a newline character by default. That's why your output is split across lines instead of matching the original sentence's spacing.

Simple Solution (Basic Spacing)

Instead of printing each word individually, we can first process all the words into a new list, then join them back together with spaces before printing. Here's the adjusted code:

print("This is the PARROT Translator!")
original = input("Please enter a sentence you want to translate: ")
words = original.split()
# Process each word and store in a new list
translated_words = [word + "pa" for word in words]
# Join the list into a single string with spaces, then print
print(' '.join(translated_words))

Preserving Exact Original Formatting (Multiple Spaces/Tabs)

If you need to keep things like multiple spaces, tabs, or other whitespace exactly as they were in the input, we can use a regex split to preserve those whitespace characters. Here's how:

import re

print("This is the PARROT Translator!")
original = input("Please enter a sentence you want to translate: ")
# Split the input while capturing whitespace as separate parts
parts = re.split(r'(\s+)', original)
# Only add "pa" to non-whitespace parts
translated_parts = [part + "pa" if not part.isspace() else part for part in parts]
# Join everything back together
print(''.join(translated_parts))

This way, if your input has something like "Hello world!" (three spaces between words), the output will be "Hellopa worldpa!" instead of collapsing the spaces to one.

Quick Test Example

If you input "Hello there friend", the first solution will output "Hellopa therepa friendpa"—exactly the sentence structure you want, no extra newlines.

内容的提问来源于stack exchange,提问作者Murg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:49:23