[英]How to split text by comma into lines?
How to split a line of text by comma onto separate lines?如何用逗号将一行文本拆分成单独的行?
text = "ACCOUNTNUMBER=Accountnumber,ACCOUNTSOURCE=Accountsource,ADDRESS_1__C=Address_1__C,ADDRESS_2__C"
fields = text.split(",")
text = "\n".join(fields)
But "\n" did not work.但是“\n”不起作用。 The result expected is that it adds new lines like:预期的结果是它添加了新行,例如:
ACCOUNTNUMBER=Accountnumber,
ACCOUNTSOURCE=Accountsource,
ADDRESS_1__C=Address_1__C,
ADDRESS_2__C
Note: I run it on Google Colab注意:我在 Google Colab 上运行它
if you want the commas to stay there you can use this code:如果您希望逗号保留在那里,您可以使用以下代码:
text = "ACCOUNTNUMBER=Accountnumber,ACCOUNTSOURCE=Accountsource,ADDRESS_1__C=Address_1__C,ADDRESS_2__C"
fields = text.split(",")
print(",\n".join(fields))
Your code should give this output你的代码应该给这个 output
ACCOUNTNUMBER=Accountnumber
ACCOUNTSOURCE=Accountsource
ADDRESS_1__C=Address_1__C
ADDRESS_2__C
But if you want to seperate it by commas(,).但是如果你想用逗号(,)分隔它。 You should add comma(,) with \n
use text = ",\n".join(fields)
instead of text = "\n".join(fields)
So the final code should be你应该添加逗号(,)与\n
使用text = ",\n".join(fields)
而不是text = "\n".join(fields)
所以最终代码应该是
text="ACCOUNTNUMBER=Accountnumber,ACCOUNTSOURCE=Accountsource,ADDRESS_1__C=Address_1__C,ADDRESS_2__C"
fields = text.split(",")
text = ",\n".join(fields)
print (text)
It will give your desirable output.它会给你想要的 output。
A more cross-compatible way could be to use os.linesep
.一种更交叉兼容的方法可能是使用os.linesep
。 It's my understanding that it's safer to do this for code that might be running on both Linux, Windows and other OSes:据我了解,对于可能在 Linux、Windows 和其他操作系统上运行的代码执行此操作更安全:
import os
print("hello" + os.linesep + "fren")
I try to use print then it worked,, thank all you guys我尝试使用 print 然后它起作用了,谢谢大家
You can use replace():您可以使用替换():
text = "ACCOUNTNUMBER=Accountnumber,ACCOUNTSOURCE=Accountsource,ADDRESS_1__C=Address_1__C,ADDRESS_2__C"
print(text.replace(',',",\n"))
result:结果:
ACCOUNTNUMBER=Accountnumber,
ACCOUNTSOURCE=Accountsource,
ADDRESS_1__C=Address_1__C,
ADDRESS_2__C
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.