具有 % 的 Python 字符串格式化程序 [英] Python String Formatter having %

查看:48
本文介绍了具有 % 的 Python 字符串格式化程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当字符串类似于以下内容时很简单:

s = 'test%s1's % '测试'

但是,当 % 本身出现在字符串中时,我会收到此错误.例如:

s = 'test%s12%34's % '测试'>>ValueError: 格式不完整

如何处理这个案子??

解决方案

加倍%:

s = 'test%s12%%34'

在输出时,它会再次折叠成一个百分号:

<预><代码>>>>s = '测试%s12%%34'>>>s % '测试''testTEST12%34'

来自字符串格式化操作文档,其中记录了各种转换字符:

<块引用>

'%' 不转换任何参数,结果中产生一个 '%' 字符.

其中第二个 % 是转换字符.

It's simple when the string is something like:

s = 'test%s1'
s % 'TEST'

However, when % itself is present in the string, then I'm getting this error. eg:

s = 'test%s12%34'
s % 'TEST'
>>ValueError: incomplete format

How to handel this case ??

解决方案

Double the %:

s = 'test%s12%%34'

On output it'll be collapsed again to a single percent symbol:

>>> s = 'test%s12%%34'
>>> s % 'TEST'
'testTEST12%34'

From the String Formatting Operations documentation, where the various conversion characters are documented:

'%' No argument is converted, results in a '%' character in the result.

where the second % is the conversion character.

这篇关于具有 % 的 Python 字符串格式化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆