如何将此循环的输出转换为此格式的字符串?
ABCDEF,BCDEFG,CDEFGH,DEFGHI
|
urls.txt:
fileHandle = open( 'urls.txt', 'r' )
raw_URLS = fileHandle.readlines()
for items in raw_URLS:
print(items[26:32])
fileHandle.close()
答案 0 :(得分:1)
您可以在列表理解中使用str.join
:
data = ','.join([item[26:32] for item in open( 'urls.txt', 'r' )])
答案 1 :(得分:0)
您可以创建一个变量来在循环之前存储字符串,然后迭代连接字符串的循环。
您的代码看起来像这样:
string_you_want = ''
fileHandle = open( 'urls.txt', 'r' )
raw_URLS = fileHandle.readlines()
for items in raw_URLS:
string_you_want = string_you_want + items[26:32] + ','
print(items[26:32])
fileHandle.close()
答案 2 :(得分:0)
试试这个:
f=open("urls.txt")
for line in f:
print (line[26:32])
答案 3 :(得分:0)
如果您的网址格式相同,请尝试:
import re
result=[]
pattern=r'[A-Z]+'
with open('new_file.txt','r') as f:
for line in f:
if re.search(pattern,line):
result.append(re.search(pattern,line).group())
print(result)
输出:
['ABCDEF', 'BCDEFG', 'CDEFGH', 'DEFGHI']