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

Python3实现小盒子尺寸输入无换行x拼接的技术问题咨询

Fixing In-Line Output for Box Dimension Formatting

Hey there! Let's figure out why your formatted box dimensions are showing up on a new line, and how to get them to display right next to your input prompt.

The Root Cause

When you use input(), once the user types their input and hits enter, the console automatically moves the cursor to the next line. Your print() statement then adds another newline by default, which is why your 1x1x1 ends up on its own line instead of staying with the input prompt.

Solution 1: Use sys.stdout.write() for Precise Control

Unlike print(), sys.stdout.write() doesn't add an automatic newline character. This lets you output your formatted text exactly where you want it. Here's how to adjust your code:

import sys

# Get user input
sb = input("Width, Height and Depth of small box: ")
# Format the input with 'x' separators
formatted_dimensions = 'x'.join(sb)
# Write the result without an extra newline (add '\n' at the end if you want a line break afterward)
sys.stdout.write(formatted_dimensions + '\n')

Solution 2: Use ANSI Escape Sequences to Rewrite the Line

If you want the formatted dimensions to replace the raw input on the same line as the prompt, you can use ANSI escape codes to move the cursor back to the start of the line and rewrite the content:

sb = input("Width, Height and Depth of small box: ")
formatted_dimensions = 'x'.join(sb)
# \r moves the cursor to the start of the current line
print(f"\rWidth, Height and Depth of small box: {formatted_dimensions}", end='')
# Use end='' to prevent an automatic newline, so the output stays on the same line

Note for Your Scoring System

Make sure to check if the scoring system expects any specific line endings or formatting. For example, if it requires the output to be on the same line as the prompt without any trailing newlines, adjust the end parameter or omit the final \n in sys.stdout.write() accordingly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:16:41