Python 中以固定宽度打印字符串
使用格式化的字符串文字以固定宽度打印字符串,例如 print(f'{my_str: <6}')
。 我们可以在格式化的字符串文字内使用表达式,我们可以在其中指定字符串的宽度和对齐方式。
my_str = 'hi'
# ✅ 打印固定宽度为 6 的字符串(左对齐)
result = f'{my_str: <6}'
print(repr(result)) # 👉️ 'hi '
# --------------------------------------------------
# ✅ 打印固定宽度为 6 的字符串(右对齐)
result = f'{my_str: >6}'
print(repr(result)) # 👉️ ' hi'
# --------------------------------------------------
result = f'{my_str: <4}world'
print(repr(result)) # 👉️ 'hi world'
# --------------------------------------------------
# 👇️ 如果将宽度存储在变量中
width = 6
result = f'{my_str: <{width}}'
print(repr(result)) # 👉️ 'hi '
我们使用格式化的字符串文字以固定宽度打印字符串。
请注意
,我使用repr()
函数还打印字符串的引号,以更好地说明字符串如何填充空格。
如果不需要,可以删除对 repr()
的调用。
result = f'{my_str: >6}'
# 👇️ with repr(), shows quotes
print(repr(result)) # 👉️ ' hi'
# 👇️ without repr(), doesn't show quotes
print(result) # 👉️ hi
格式化字符串文字(f-strings)让我们通过在字符串前面加上 f 来在字符串中包含表达式。
my_str = 'is subscribed:'
my_bool = True
result = f'{my_str} {my_bool}'
print(result) # 👉️ is subscribed: True
确保将表达式包裹在花括号 - {expression}
中。
格式化的字符串文字还使我们能够在表达式块中使用特定于格式的迷你语言。
my_str = 'hi'
# 👇️ left-aligned
result = f'{my_str: <6}'
print(repr(result)) # 👉️ 'hi '
# 👇️ right-aligned
result = f'{my_str: >6}'
print(repr(result)) # 👉️ ' hi'
冒号和小于号之间的空格是填充字符。
my_str = 'hi'
result = f'{my_str:.<6}'
print(repr(result)) # 👉️ 'hi....'
result = f'{my_str:.>6}'
print(repr(result)) # 👉️ '....hi'
上面的示例使用句点作为填充字符而不是空格。
小于或大于号是对齐方式。
小于号使字符串向左对齐,大于号使字符串向右对齐。
符号后面的数字是字符串的宽度。
print(repr(f'{"hi": <6}')) # 👉️ 'hi '
print(repr(f'{"hii": <6}')) # 👉️ 'hii '
print(repr(f'{"hiii": <6}')) # 👉️ 'hiii '
print(repr(f'{"hiiii": <6}')) # 👉️ 'hiiii '
print(repr(f'{"hiiiii": <6}')) # 👉️ 'hiiiii'
请注意,我使用单引号将 f
字符串和双引号括在其中。
重要的是在单引号和双引号之间交替以避免过早终止 f
字符串。
如果我们将字符串的宽度存储在变量中,请确保将其包裹在 f
字符串中的花括号中。
width = 6
result = f'{my_str: <{width}}'
print(repr(result)) # 👉️ 'hi '
请注意
,我们使用了一组额外的花括号来计算小于号之后的宽度变量。
相关文章
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串
在 Python Pandas 中使用 str.split 将字符串拆分为两个列表列
发布时间:2024/04/24 浏览次数:1124 分类:Python
-
本教程介绍如何使用 pandas str.split() 函数将字符串拆分为两个列表列。
在 Pandas 中将 Timedelta 转换为 Int
发布时间:2024/04/23 浏览次数:231 分类:Python
-
可以使用 Pandas 中的 dt 属性将 timedelta 转换为整数。
Python 中的 Pandas 插入方法
发布时间:2024/04/23 浏览次数:112 分类:Python
-
本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。
使用 Python 将 Pandas DataFrame 保存为 HTML
发布时间:2024/04/21 浏览次数:106 分类:Python
-
本教程演示如何将 Pandas DataFrame 转换为 Python 中的 HTML 表格。
如何将 Python 字典转换为 Pandas DataFrame
发布时间:2024/04/20 浏览次数:73 分类:Python
-
本教程演示如何将 python 字典转换为 Pandas DataFrame,例如使用 Pandas DataFrame 构造函数或 from_dict 方法。
如何在 Pandas 中将 DataFrame 列转换为日期时间
发布时间:2024/04/20 浏览次数:101 分类:Python
-
本文介绍如何将 Pandas DataFrame 列转换为 Python 日期时间。