刚发现 Python 一个现象,求解释

2019-04-11 14:07:44 +08:00
 MartinWu
long_str = ("This is a long %s" % "story." "And you are welcome to %s." % "listen")

是没有语法错误的。 然后,

long_str = ("It is %d stories." % 3 )

也是没问题的。 最后,

long_str = ("我编不下去了,随便搞%d 个测试" % 123 "这是一个%s 测试啊" % "有趣的")

就是说这种方式来组合字符串, % 后的元素穿插在中间的,只能是字符串,其他类型元素,只能安排在最后。 不然会报语法错误。大家知道是那部分的 python 文档解释到吗?

2661 次点击
所在节点    Python
12 条回复
wnh3yang
2019-04-11 14:15:23 +08:00
我不是程序员,但我看出来错误了。

<img src="https://img.vim-cn.com/ff/7eeb833337ed48124facf6489efb169a13a141.png" alt="">

两个字符串放一起会自动拼成一个字符串, 数字和字符串放一起报语法错误。
lithiumii
2019-04-11 14:17:45 +08:00
% 是用来把变量插到字符串里面的,当然是完整的字符串写前面,别的扔后面……
但是,我从来没学会过用 %,跟谜语似的。反正你写 py 的话建议用 str.format(),比如:

long_str = ("我编不下去了,随便搞{}个测试这是一个{}测试啊".format(123, "有趣的"))

https://docs.python.org/3.7/library/string.html#formatstrings
MartinWu
2019-04-11 14:21:47 +08:00
@lithiumii #2 但是我觉得你的这个解释没法解释为什么:

``` python
long_str = ("This is a long %s" % "story." "And you are welcome to %s." % "listen")
```

语法没报错,这也是中间穿插了一个 % 渲染,只是这里是"story" 而不是 123。
besto
2019-04-11 14:23:32 +08:00
123 '错误'
'123' '正确'

好理解一点了么
Alexhex
2019-04-11 14:26:35 +08:00
你试着 print 一下第一个。
Alexhex
2019-04-11 14:31:49 +08:00
说错了,你试着 print 一下下面这个:

long_str = ("This is a long %s, but" % "story." " you are welcome to %s." % "listen")
wnh3yang
2019-04-11 14:33:26 +08:00
@MartinWu

我觉得是运算优先级的问题:

``` python
long_str = ("This is a long %s" % "story." "And you are welcome to %s." % "listen")
```

"story." "And you are welcome to %s." 最先合并成一个字符串。会变成:
``` python
long_str = ("This is a long %s" % "story.And you are welcome to %s." % "listen")
```

再变成
``` python
long_str = ("This is a long %s" % "story.And you are welcome to listen.")
```

再变成
``` python
long_str = ("This is a long story.And you are welcome to listen.")
```


所以
``` python
long_str = ("我编不下去了,随便搞%d 个测试" % 123 "这是一个%s 测试啊" % "有趣的")
```

123 "这是一个%s 测试啊"

这个数字和字符串合并的过程会报语法错误
LFly
2019-04-11 14:36:55 +08:00
print(123 "long str")
print("123" "long str")
long_str = ("我编不下去了,随便搞%s 个测试" % 123, "这是一个%s 测试啊" % "有趣的")
Tink
2019-04-11 14:37:41 +08:00
"123"
lihnzx
2019-04-11 14:42:03 +08:00
"我编不下去了,随便搞%d 个测试" % 123 + "这是一个%s 测试啊" % "有趣的"

没明白你的意思
拼接字符串使用 format 或 join 性能更高一点
rrfeng
2019-04-11 14:50:03 +08:00
("aaaa" "bbbbb") == ("aaaabbbbb")
(3 "aaaaaa") = error


看懂这个就好了跟 % 没关系
lithiumii
2019-04-11 15:01:38 +08:00
@MartinWu
圆括号里面放字符串并且不加逗号,视同一个长的字符串,放别的类型不行

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

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

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

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

© 2021 V2EX