现在我在每一行后面都有逗号,但我需要在每两行后面插入逗号。这是我正在编写的文本。 产品规格:
LEVERANDØRENS VARENUMMER 31358DC2 EAN NUMMER 4005176465017
这是我的密码:
specification.text.replace("\n",",").strip()
我的代码在每一行的末尾给我逗号,但我需要在每两行后面加逗号。以下是我的结果:
LEVERANDØRENS VARENUMMER,31358DC2,EAN NUMMER,4005176465017
我的预期结果如下:
LEVERANDØRENS VARENUMMER 31358DC2,EAN NUMMER 4005176465017
编辑:我只建议在您试图避免使用外部库时使用此方法。如果您可以访问像itertools这样的库(在Jason的回答中提到),您应该使用它们
这并不完全是小事。我组合的这个函数应该满足您的要求(增加了每N个字符执行一次的功能,而不仅仅是每两个字符执行一次)
在您的特定情况下,您可以这样使用:
您可以编写一个生成器,成对地迭代行。用空格连接它们,然后用逗号连接那个
您可以使用pythonshell来探索这个解决方案,并根据需要添加功能
拆分该行将为您提供一个行列表,如果您愿意,可以进一步处理这些行
一次抓取两行可以得到元组
这些块可以通过多种方式进行处理。除了与空格连接外,还可以使用格式说明符
您可以使用此行以逗号连接每两行:
输出:
另外,如果您知道行数始终为偶数,那么您可以简化解决方案,只需
zip
即可解决问题:相关问题 更多 >
编程相关推荐