简体   繁体   English

Python:如何将字符串块转换为一行

[英]Python: How to transform a block of strings into one line

This is the text block that I want to transform to another form: 这是我想转换为另一种形式的文本块:

1040 S. Vintage Ave.
Building A Ontario, CA 91761
United States 

This is the wanted output: 这是所需的输出:

1040 S. Vintage Ave., Building A Ontario, CA 91761,United States  

I've tried to use split, and replace, also some re expression but I couldn't make it work. 我尝试过使用分割和替换以及一些重新表达,但是我无法使其正常工作。

Any suggestion would be helpful :) 任何建议都会有所帮助:)

Considering the block text is in a file: 考虑块文本在文件中:

list.txt: LIST.TXT:

1040 S. Vintage Ave.

Building A Ontario, CA 91761
United States 

and then: 接着:

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: OUTPUT:

1040 S. Vintage Ave., Building A Ontario,  CA 91761, United States

multiline_string.replace('\\ n','')或被'\\ n'分割并加入空字符('')

If your text is in a variable called text : 如果您的文本位于名为text的变量中:

one_line = text.replace("\n", ", ")

That replaces the end of each line with a comma, putting it all on one line. 这样用逗号替换了每一行的末尾,将它们全部放在一行上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM