[英]Python: How to transform a block of strings into one line
这是我想转换为另一种形式的文本块:
1040 S. Vintage Ave.
Building A Ontario, CA 91761
United States
这是所需的输出:
1040 S. Vintage Ave., Building A Ontario, CA 91761,United States
我尝试过使用分割和替换以及一些重新表达,但是我无法使其正常工作。
任何建议都会有所帮助:)
考虑块文本在文件中:
LIST.TXT:
1040 S. Vintage Ave.
Building A Ontario, CA 91761
United States
接着:
logFile = "list.txt"
with open(logFile) as f:
content = f.readlines()
# you may also want to remove empty lines
content = [l.strip() for l in content if l.strip()]
lastLine = content[-1]
for line in content:
findComma = line.find(",")
if findComma > 0:
print(line.split(",")[0] + ", ", end = "")
print(line.split(",")[1] + ", ", end = "")
else:
if line != lastLine:
print(line + ", ", end = "")
else:
print(line, end = "")
OUTPUT:
1040 S. Vintage Ave., Building A Ontario, CA 91761, United States
multiline_string.replace('\\ n','')或被'\\ n'分割并加入空字符('')
如果您的文本位于名为text
的变量中:
one_line = text.replace("\n", ", ")
这样用逗号替换了每一行的末尾,将它们全部放在一行上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.