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

Python 3.6含用户输入变量的文本居中问题求助

问题分析与解决办法

Hey there! Let's break down what's going wrong with your code and fix it.

问题根源

Your format() call has a mismatch between the placeholder count and the arguments you're passing. The format string "{: ^80}" only has one placeholder, but you're sending three separate values: "You are", age, and "years old.".

Python handles this by packing those three values into a tuple, then converting the entire tuple to a string. So instead of getting the sentence "You are 40 years old." centered, you're actually getting something like ('You are', '40', 'years old.') centered—definitely not what you want!

几种可行的解决方案

1. 先拼接完整句子,再格式化居中

First, build your full sentence, then apply the centering formatting to that single string:

age = input("How old are you? ")
full_sentence = f"You are {age} years old."  # 使用f-string拼接(Python 3.6+)
print("{: ^80}".format(full_sentence))

Or if you prefer using str.format() for the sentence:

age = input("How old are you? ")
full_sentence = "You are {} years old.".format(age)
print("{: ^80}".format(full_sentence))

2. 在格式化字符串中直接包含所有占位符

You can combine the sentence construction and centering in one step by adding placeholders for the age inside the centered format string:

age = input("How old are you? ")
print("{: ^80}".format("You are {} years old.".format(age)))

3. 使用字符串的center()方法(最直观)

Python strings have a built-in center() method that does exactly what it sounds like—centers the string within a specified width. This is often the cleanest approach:

age = input("How old are you? ")
print(f"You are {age} years old.".center(80))

Or if you want to stick with the format specifier style:

age = input("How old are you? ")
print(f"{'You are ' + age + ' years old.': ^80}")

All these approaches will give you the properly centered full sentence you're aiming for.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:10:33