Python-str 数据结构
str 基础
格式化字符串
使用%格式化
"Old Style" String Formatting ( %
Operator):
'Hello, %s' % name
: format string value'%x' % errno
: use the%x
format specifier to convert an int value to a string'Hey %(name)s, there is a 0x%(errno)x error!' % {"name": name, "errno": errno }
:%
format with dict
使用 format 关键字
"New Style" String Formatting ( str.format
)(坏处是如果有大量的元素要赋值要写多个赋值符号,此时可以生成一个dict然后 unpackage 这个 dict, 或者升级 python 用f-string)
"Hello, {}. You are {}.".format(name, age)
: replace fields are marked by curly braces"Hello, {1}. You are {0}.".format(age, name)
: reference variables by their index- with param assignment
person = {'name': 'Eric', 'age': 74} "Hello, {name}. You are {age}.".format(name=person['name'], age=person['age'])
- unpackage with dict
person = {'name': 'Eric', 'age': 74} "Hello, {name}. You are {age}.".format(**person)
format 关键字的更多扩展
format 可以扩展很多格式
^ < >
: 分别表示居中 左对齐 右对齐 后面带宽度:
号后面带填充的字符 只能是一个字符 不指定则默认是用空格填充+
: 表示在正数前显示*+* 负数前显示 - (空格)表示在正数前加空格b d o x
: 分别是二进制(Binary system) 十进制(Decimal system) 八进制(Octal number system) 十六进制(Hexadecimal){}
: 使用大括号 {} 来转义大括号
相关例子如下:
f stand for float, d stand for decimal
{:.2f}
: 保留小数点后两位"{:.2f}".format(3.1415926); "3.14"
{:+.2f}
: 带符号保留小数点后两位"{:.2f}".format(3.1415926); "+3.14"
{:.0f}
: 不带小数{:0>2d}
: 数字补零 (填充左边, 宽度为 2)"{:0>2d}".format(5); "05"
{:x<4d}
: 数字补 x (填充右边, 宽度为 4)"{:x<4d}".format(5); 5xxx
{:,}
: 以逗号分隔的数字格式"{:,}".format(1000000); 1,000,000
{:.2%}
: 两位小数百分比格式"{:.2%}".format(0.256); 25.60%
{:10d}
: 右对齐(默认) 宽度为 10"{:10d}".format(13); " 13"
{:<10d}
: 左对齐宽度为 10"{:<10d}".format(13); "13 "
{:^10d}
: 中间对齐 宽度为 10"{:^10d}".format(13); " 13 "
使用 f-strings 格式化
关于 f-strings
The f in f-strings may as well stand for fast:f-strings are faster than both %
-formatting and str.format()
. As you already saw, f-strings are expressions evaluated at runtime rather than constant values. Here’s an excerpt from the docs
“F-strings provide a way to embed expressions inside string literals, using a minimal syntax. It should be noted that an f-string is really an expression evaluated at run time, not a constant value. In Python source code, an f-string is a literal string, prefixed with f, which contains expressions inside braces. The expressions are replaced with their values.” ( Source )
f-strings 格式化
f-Strings: A New and Improved Way to Format Strings in Python 3.6
- similar to the
str.format()
but less verbosename = "Eric" age = 74 f"Hello, {name}. You are {age}."
- Arbitrary Expressions: Because f-strings are evaluated at runtime, you can put any and all valid Python expressions in them. This allows you to do some nifty things
f"{2 * 37}"
: return '74'name = "Eric Idle"; f"{name.lower()} is funny."
: lower the str, return 'eric idle is funny.'- user defind function
def to_lowercase(input): return input.lower() name = "Eric Idle" f"{to_lowercase(name)} is funny." # 'eric idle is funny.'
str 内置函数
split
S.split(sep=None, maxsplit=-1) -> list of strings
Return a list of the words in S, using sep as the
delimiter string. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified or is None, any
whitespace string is a separator and empty strings are
removed from the result.
rsplit
at the end of the string and working to the front
S.rsplit(sep=None, maxsplit=-1) -> list of strings
Return a list of the words in S, using sep as the
delimiter string, starting *at the end of the string and
working to the front*. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified, any whitespace string
is a separator.
find
find(...)
S.find(sub [,start [,end]]) -> int
Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
rfind
rfind(...)
S.rfind(sub [,start [,end]]) -> int
Return the highest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
FAQ
如果格式化含有{}的字符串
如果格式化的字符串中含有 {}
,则需要使用两个 {{}}
,参考 这里
>>> x = " {{ Hello }} {0} "
>>> print(x.format(42))
' { Hello } 42 '
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
上一篇: Python-list 数据结构
下一篇: Covenant 利用分析
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论