Coalesce terminal output strings into one string with Python
<p>I am trying to fetch the output of the <code>fortune</code> command and send it to web-based WhatsApp. I am able to fetch the output from the <code>fortune</code> command, but when I send it to WhatsApp, the <code>fortune</code> output is outputted as separate lines/messages. How do I make them into one and send it as a single message? Thanks. </p>

<pre><code>fortune_list = ["(?i)art","(?i)comp","(?i)cookie","(?i)drugs","(?i)education","(?i)ethnic","(?i)food"]

for i in range(len(fortune_list)):
    if re.search(re.compile(fortune_list[i]),reply):
        cmd = ['fortune', fortune_list_reply[i]]
        output = subprocess.Popen( cmd, stdout=subprocess.PIPE ).communicate()[0]
        print output
        input_box[1].send_keys(output)
        time.sleep(1)
        b.find_element_by_class_name('send-container').click() 
</code></pre>

<p>The output on the terminal (<code>print output</code>)</p>

<p><a href="http://i.stack.imgur.com/YXo93.png" rel="nofollow"><img src="http://i.stack.imgur.com/YXo93.png" alt="enter image description here"></a></p>

<p>The ouput sent on WhatsApp as seperate messages.</p>

<p><a href="http://i.stack.imgur.com/Lj2vT.png" rel="nofollow"><img src="http://i.stack.imgur.com/Lj2vT.png" alt="enter image description here"></a></p>

<p>Desired output as a single message.</p>

<p><a href="http://i.stack.imgur.com/dFYao.png" rel="nofollow"><img src="http://i.stack.imgur.com/dFYao.png" alt="enter image description here"></a></p>

<p><strong><em>Edit 1 :</em></strong> Using <code>repr</code> : Coalesces the strings but with these characters. Using regex replace to replace the characters isn't working.</p>

<p><code>"XXXI:\n\tThe optimum committee has no members.\nXXXII:\n\tHiring consultants to conduct studies can be an excellent means of\n\tturning problems into gold -- your problems into their gold.\nXXXIII:\n\tFools rush in where incumbents fear to tread.\nXXXIV:\n\tThe process of competitively selecting contractors to perform work\n\tis based on a system of rewards and penalties, all distributed\n\trandomly.\nXXXV:\n\tThe weaker the data available upon which to base one's conclusion,\n\tthe greater the precision which should be quoted in order to give\n\tthe data authenticity.\n\t\t-- Norman Augustine\n"</code></p>

<p><strong><em>Edit 2:</em></strong> Answer added.</p>

<p>To coalesce the output strings of terminal into one, split the output at new lines and store them in a list. </p>

<pre><code>sentence = ""
cmd = ['fortune', fortune_list_reply[i]]
output = subprocess.Popen( cmd, stdout=subprocess.PIPE ).communicate()[0]
output = output.split('\n')
for string in output:
    string = string.split("\t")                                     
    for substring in string:
        if len(substring) == 0:
            continue
        else:
            sentence = sentence + " " + substring
</code></pre>

python shell selenium terminal command