簡體   English   中英

Python:如何將字符串塊轉換為一行

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM