[Python 语法] 询问在 String 中关于 % 的用法(找不到相关文档)

2016-01-25 22:41:07 +08:00
 terence4444
请问以下的用法相关文档可以在哪里找到?我想知道是否关于 % 还有其它用法。

string1 = 'string replace %s'
string2 = 'abcdefg'
string3 = string1 % string2
>> string3 == 'string replace abcdefg'

谢谢
4142 次点击
所在节点    Python
36 条回复
zk8802
2016-01-25 22:46:49 +08:00
terence4444
2016-01-25 22:52:21 +08:00
@zk8802 感谢,连页面 tag 都打好了,太贴心 :)
ethego
2016-01-25 22:55:35 +08:00
建议使用 format 方法,%什么的估计只有写 c 的转 python 才会用。"{0}, {1}{2}".format("hello", "world", 1) >>> "hello, world1"
terence4444
2016-01-25 23:02:31 +08:00
@ethego 感谢,我在文档中看到这个写法和 format 写法等同的,我本来要写动态 SQL 用的……

sql_cause = "replace into tabls(%(fields)s) values(%(values)s) "
params = {'fields': 'f1,f2,f3', 'values': 'v1,v2,v3'}
sql_cause = sql_cause % params

用 format 应该可以等同为(还没测):
"replace into tabls({0}) values({1}) ".format('f1,f2,f3', 'v1,v2,v3')

Python 推荐用第二种吗?
ethego
2016-01-25 23:05:05 +08:00
@terence4444 推荐第二种,比第一种更加简洁明了,还不用考虑类型的问题
ethego
2016-01-25 23:09:05 +08:00
@terence4444 写 sql 拼接字符串,小心 sql 注入
terence4444
2016-01-25 23:15:15 +08:00
@ethego 谢谢提醒
这个是我自己跑定时任务抓东西用的, field 和 value 都是固定写死的几个字段的排列组合(抓到某个值就写上字段和值,没有抓到的就跳过不更新)
没有用户输入,应该没有关系吧…… 有用户输入的肯定会 encode 一下的。
qihboy
2016-01-25 23:19:38 +08:00
% 是 python 的表达式
.format 是方法,现在推荐用 format 而已
vmebeh
2016-01-25 23:23:32 +08:00
拼接 sql 语句不安全,用 ? 占位, tuple 传值


https://docs.python.org/2/library/sqlite3.html

```# Never do this -- insecure!
symbol = 'RHAT'
c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)

# Do this instead
t = ('RHAT',)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)
print c.fetchone()
```
fy
2016-01-25 23:50:15 +08:00
@qihboy 咦,请问 python 推荐用 format ,有出处吗?
一直在用 %s 来输出全部类型……
necomancer
2016-01-26 01:54:53 +08:00
RqPS6rhmP3Nyn3Tm
2016-01-26 02:00:45 +08:00
写了这么久第一次知道还有 format 写法,果然写 C 写习惯了……
guoqiao
2016-01-26 03:23:34 +08:00
@ethego 还可以更简单:

"{}, {}{}".format("hello", "world", 1) >>> "hello, world1"
leavic
2016-01-26 09:19:26 +08:00
习惯了 format 写法,我都快忘记%方法怎么写了
nellace
2016-01-26 09:25:38 +08:00
习惯了%,不知道耗能 format
qihboy
2016-01-26 09:42:20 +08:00
@fy https://docs.python.org/2/library/stdtypes.html#str.format

This method of string formatting is the new standard in Python 3, and should be preferred to the % formatting described in String Formatting Operations in new code.

New in version 2.6.
Karblue
2016-01-26 10:07:19 +08:00
%写法写起来更快 。 format 都懒得敲
huangfs
2016-01-26 10:19:03 +08:00
也是习惯%
TheCure
2016-01-26 10:37:03 +08:00
这东西叫占位符
要是你知道这叫占位符,搜起来就很快了
pynix
2016-01-26 10:44:58 +08:00
字符串插值, format 是 Java 那边搞过来的,有点背道而驰。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/253341

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX