简体   繁体   中英

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:

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:

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 :

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

That replaces the end of each line with a comma, putting it all on one line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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