python - 根据python中的用户输入对齐文本

标签 python

aStr = input("Enter a string message: ")
fW = eval(input("Enter a positive integer: "))
print(f"Right aligned is <{aStr:>fW}>")

所以,这是我的代码,我想根据用户输入对齐空格。每当我尝试在 fW 中使用 eval 或 int 时,它都会显示此错误。

Traceback (most recent call last):
  File "C:\Users\vmabr\Downloads\A1Q2.py", line 5, in <module>
    print(f"Right aligned is <{aStr:fW}>")
ValueError: Invalid format specifier

我可以知道解决方法是什么吗?

最佳答案

你很接近。要实现“参数化”格式字符串,您需要将参数 fW 包装到额外的大括号中:

aStr = input("Enter a string message: ")
fW = int(input("Enter a positive integer: "))
print(f"Right aligned is <{aStr:>{fW}}>")  # {fW} instead of fW

参见 PEP 498 -> format specifiers了解更多信息。

关于python - 根据python中的用户输入对齐文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74097495/

相关文章:

python - 按下 escape 时取消输入

python - 我怎样才能打开一个文件并遍历它,只从某些行添加数据?

javascript - 错误选项 net::ERR_CONNECTION_REFUSED

python - Flask+nginx+gunicorn 重定向错误

python - "TypeError: ' NoneType ' object is not iterable"来自 pandas read_sql

python - 第二次迭代文件不起作用

python - python 中的 TCP 跟踪路由

python - 关系不存在 Django Postgres

python - 如何从查询集 Django 中获取包含所有数据的特定列表?

python - 使用 python 创建蜂鸣器系统