Python鹦鹉翻译器split后输出格式不符合预期问题求助
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

