我有一个名为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!
答案 0 :(得分:1)
例如,您可以这样做:
file = open("url.txt","r")
for line in file:
myUrl = "\"" + line[:-1] + "\""
print(myUrl)
\
用于转义"
,因为它是保留符号。
+
用于在此处连接字符串。
line[:-1]
用于从line
中删除结尾的换行符。
此解决方案假定注释中提到的deceze♦保证尾随换行符。
使用'"'
提及的deceze♦也更简单,所以我现在改用它。
使用以下解决方案,您还可以读取给定行中的多个URL,这些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"
答案 1 :(得分:-1)
我们可以直接提供报价。
file = open("url.txt","r")
for line in file:
myUrl = line
print('"',myUrl,'"')