在尝试从txt文件中获取数据时,我遇到了一个问题。解决办法肯定很简单,但无论如何,我想我需要你的一点帮助。现在它打印的像'123 123456',但我想打印它像'123 456',有什么想法吗?
输入
asd
ear
hello
hello
hello
rea
ear
world
world
rea
zxczxc代码
check = False
data = ''
start = 'ear'
end = 'rea'
with open('bear.txt', 'r') as rf:
lines = rf.readlines()
for i,x in enumerate(lines):
if start in x:
check = True
if check:
data += str(x)
if end in x:
check = False
print(data)
print(i)输出
ear
hello
hello
hello
rea
5
ear
hello
hello
hello
rea
ear
world
world
rea
9预期产出
ear
hello
hello
hello
rea
5
ear
world
world
rea
4发布于 2019-09-27 18:31:26
check = False
data = ''
start = 'ear'
end = 'rea'
with open('bear.txt', 'r') as rf:
lines = rf.readlines()
for x in lines:
if start in x:
check = True
if check:
data += str(x)
if end in x:
check = False
print(data)
# Count of data that split by `\n`
# However, there is one extra `\n` so minus 1.
print(len(data.split("\n")) - 1)
# If it is not initialized, the contents will remain intact
data = ''发布于 2019-09-27 18:24:02
需要重新初始化data的
check = False
data = ''
start = 'ear'
end = 'rea'
with open('temp.txt', 'r') as rf:
lines = rf.readlines()
for i,x in enumerate(lines):
if start in x:
check = True
if check:
data += str(x)
if end in x:
check = False
print(data)
print(i)
data = ''输出:
ear
hello
hello
hello
rea
5
ear
world
world
rea
9https://stackoverflow.com/questions/58139629
复制相似问题