从python文件打印URL时,在URL中添加引号
我有一个名为url.txt的文件。里面有几个URL。我想打印来自它的URL。例如:www.google.com。当我打印它时,它打印为www.google.com。但我想打印www.google.com,并引用www.google.com。这是我的代码:从python文件打印URL时,在URL中添加引号,python,python-3.x,Python,Python 3.x,我有一个名为url.txt的文件。里面有几个URL。我想打印来自它的URL。例如:www.google.com。当我打印它时,它打印为www.google.com。但我想打印www.google.com,并引用www.google.com。这是我的代码: file = open("url.txt","r") for line in file: myUrl = line print(myUrl) 它打印为www.google.com 例如,您可以: file = open("u
file = open("url.txt","r")
for line in file:
myUrl = line
print(myUrl)
它打印为www.google.com 例如,您可以:
file = open("url.txt","r")
for line in file:
myUrl = "\"" + line[:-1] + "\""
print(myUrl)
\用于转义,因为它是保留符号
+用于在此处连接字符串
第[:-1]行用于从第行中删除尾随的换行符
此解决方案假定为deceze♦ 在评论中提到,保证使用尾随换行符
也有deceze♦ 前面提到的使用“”更简单,所以我现在改为使用它
使用以下解决方案,您还可以读取给定行中由分隔符分隔的多个URL[假设此分隔符使用正确]:
file = open("url.txt","r")
myUrl = []
for line in file:
delimiter = " " # enter your delimiter here
i = line.count(delimiter) # assuming delimiter is used correctly
if i > 0:
for j in range(0,i+1):
myUrl = line.split(delimiter)[j]
if j == i:
myUrl = '"' + myUrl[:-1] + '"'
print(myUrl)
continue
myUrl = '"' + myUrl + '"'
print(myUrl)
else:
myUrl = '"' + line[:-1] + '"'
print(myUrl)
假设url.txt是这样的:
www.google.com
www.amazon.com www.duckduckgo.com www.stackoverflow.com
这将打印:
"www.google.com"
"www.amazon.com"
"www.duckduckgo.com"
"www.stackoverflow.com"
我们可以直接打印报价单
file = open("url.txt","r")
for line in file:
myUrl = line
print('"',myUrl,'"')
打印“%s”%myUrl…?!打印时需要在双引号内换行:f'{line}。我使用了myUrl='%s'%line,但它打印了www.google.com。使用“”,这会更简单;只有在保证有换行符的情况下,以这种方式删除尾随的换行符才是一个好主意,否则就是切掉最后一个字符。