python - 在使用 readlines() 创建的字符串中使用 for 循环插入多行

标签 python string python-3.x readlines

我正在尝试在 python 中使用 readlines() 创建的字符串中插入多行。我对其进行了很多小时的调试,但我无法找出问题所在。

我有先前定义的 i 个服务器。 “data”是一个字符串,其中包括我的文本文档,我有一个函数“get_line”,它在字符串中搜索关键字“Queue1 Position”并返回该行。在我的示例中,该行是 82。

...

data = cfg.readlines()

...

#Queue
i = int(gwi["Server"][0]) #Number of Servers
line_idx=get_line(data,'Queue1 Position')
for x in range(1,i+1):
    if x==1:
        data[line_idx] = ('Queue'+str(x)+' Position { 1.500000  '+str(1.100000-x+1)+'  0.000000  m }\n'+'Queue'+str(x)+
        ' Points { {  1.500  '+str(0.700-x+1)+'  0.000  m  }  {  2.500  '+str(0.700-x+1)+'  0.000  m  } }\n\n')
        print(line_idx) #test
    else:
        line_idx = line_idx + 1
        data[line_idx] = ('Queue'+str(x)+' Position { 1.500000  '+str(1.100000-x+1)+'  0.000000  m }\n'+'Queue'+str(x)+
            ' Points { {  1.500  '+str(0.700-x+1)+'  0.000  m  }  {  2.500  '+str(0.700-x+1)+'  0.000  m  } }\n\n')
        print(line_idx) #test

My Document which I edit looks like that at the beginning.

When I run my code the cfg- file looks like that. 'Server1 NextComponent { EntitySink1 }' is cut.

But when I run my code the result should be like that.

是否可以用 for 循环来解决这个问题?也许还有另一种解决方案。

最佳答案

我自己解决了这个问题。

#Queue
i = int(gwi["Server"][0]) #Number of Servers
line_idx=get_line(data,'Queue1 Position')
del data[line_idx+1]
queue_text = ""
for x in range(1,i+1):
    if x<i:
        queue_text = queue_text+('Queue'+str(x)+' Position { 1.500000  '+str(1.100000-x+1)+'  0.000000  m }\n'+'Queue'+str(x)+
        ' Points { {  1.500  '+str(0.700-x+1)+'  0.000  m  }  {  2.500  '+str(0.700-x+1)+'  0.000  m  } }\n\n')
    else:
        queue_text = queue_text+('Queue'+str(x)+' Position { 1.500000  '+str(1.100000-x+1)+'  0.000000  m }\n'+'Queue'+str(x)+
        ' Points { {  1.500  '+str(0.700-x+1)+'  0.000  m  }  {  2.500  '+str(0.700-x+1)+'  0.000  m  } }\n')
data[line_idx] = queue_text

关于python - 在使用 readlines() 创建的字符串中使用 for 循环插入多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50951893/

相关文章:

c - 选择语句 IF 不起作用?

python - 将列表的列表解压缩到列表中

python - 如何通过 LightFM python 包生成用户推荐?

python - 如何在循环中追加多个 pandas DataFrame?

python - 将维基百科表格抓取到 Pandas 数据框

python - 给定位置 (X,Y) 沿第三轴 (Z) 更新 Rank3 tensorflow 张量中的切片

c++ - std::string,string val 和 string val 之间的区别 = ""

python - 从 Pandas Dataframe 列中提取字符串形式的 JSON 对象列表

Java 正则表达式与精确标记有关的问题

python-3.x - 如何将带有单引号和双引号的列表值放入 Postgresql Select Query