在Python编程中,str.format() 函数是一个十分有用的工具,它用于对字符串进行格式化。尽管可能存在误解,'strcot' 并非标准的Python函数名,这里我们假设是指 str.format()。本文将详细介绍 str.format() 的基本使用方法。 str.format() 函数允许用户在字符串中插入变量,或者按照一定的格式对字符串进行排版。其基本语法结构是使用大括号 {} 作为占位符,然后在 format() 方法中指定要插入的内容。以下是 str.format() 的一些常见用法。
基础用法
在字符串中使用 {} 作为占位符:
text = 'Hello, {}!'.format('world')
print(text) ## 输出: Hello, world!
多个占位符
可以同时使用多个占位符:
text = '{} is from {}, and {} is from {}.'.format('Alice', 'Wonderland', 'Bob', 'Builder')
print(text) ## 输出: Alice is from Wonderland, and Bob is from Builder.
指定位置
通过索引来指定占位符的位置:
text = '{1} is {0} years old.'.format(30, 'Alice')
print(text) ## 输出: Alice is 30 years old.
关键字参数
也可以使用关键字参数来指定占位符:
text = '{name} is {age} years old.'.format(name='Alice', age='30')
print(text) ## 输出: Alice is 30 years old.
数字格式化
还可以对数字进行格式化,如保留小数位数:
text = 'Pi is approximately {:.2f}.'.format(3.14159)
print(text) ## 输出: Pi is approximately 3.14.
填充与对齐
使用 format() 可以控制字符串的对齐与填充:
text = '{:>10}'.format('Python') ## 右对齐,总共10个字符宽度
print(text) ## 输出: ' Python'
text = '{:<10}'.format('Python') ## 左对齐,总共10个字符宽度
print(text) ## 输出: 'Python '
text = '{:^10}'.format('Python') ## 居中对齐,总共10个字符宽度
print(text) ## 输出: ' Python '
以上就是 str.format() 函数的详细用法。它是一个功能强大的工具,可以用于多种字符串格式化的需求。