gpt4 book ai didi

python : Trying to concatenate a simple string into a URL

转载 作者:行者123 更新时间:2023-11-28 17:01:18 27 4
gpt4 key购买 nike

我有一个从我想用作文件名的网站页面上抓取的变量“标题”。我尝试了很多组合都无济于事。我的代码有什么问题?

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')

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

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

关于 python : Trying to concatenate a simple string into a URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54375948/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com