Python:尝试将一个简单的字符串连接到URL中

2024-04-28 08:27:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个变量“title”,是我从一个网站页面上抓取的,我想用它作为文件名。 我试过很多组合都没有用。我的代码怎么了?在

f1 = open(r'E:\Dp\Python\Yt\' + str(title) + '.txt', 'w')

谢谢你


Tags: 代码txttitle网站文件名页面openf1
2条回答

需要转义他们所有的斜杠博约,否则他们将转义后面的字符。在

f1 = open(r'E:\\Dp\\Python\\Yt\\' + str(title) + '.txt', 'w')

问题中突出显示的语法应该能帮助你。\'不终止字符串它是一个转义的单勾号'。在

正如this old answer所示,实际上不可能用反斜杠结束原始字符串。最好的选择是使用字符串格式

# old-style string interpolation
open((r'E:\Dp\Python\Yt\%s.txt' % title), 'w')
# or str.format, which is VASTLY preferred in any modern Python
open(r'E:\Dp\Python\Yt\{}.txt'.format(title), 'w')
# or, in Python 3.6+, the new-hotness of f-strings
open(rf'E:\Dp\Python\Yt\{title}.txt', 'w')

或者添加更多的字符串连接,这看起来更糟。在

^{pr2}$

相关问题 更多 >