python remove last comma
<p>I have some thing like this in output.txt file</p>

<pre><code>Service1:Aborted
Service2:failed
Service3:failed
Service4:Aborted
Service5:failed
</code></pre>

<p>output in 2nd file(output2.txt) :</p>

<pre><code> Service1        Service2   Servive3   Service4     Service5
 Aborted         failed     failed     Aborted      failed
</code></pre>

<p>Would like to remove the last comma in the line.</p>

<p>Code I am trying:</p>

<pre><code>    file=open('output.txt','r')
    target=open('output2.txt','w')
    for line in file.readlines():
          line=line.strip()
          parts=line.split(":")
          for part in parts:
               var2=part.strip()+","
          target.write(var2.rstrip(','))        # Not working
   target.close()
</code></pre>

<p>I found a simple way to do it, you can of course minimize the steps, but the idea is the same, take a string, reverse it. Then use string replace with a limit of one replacement to replace all commas, this will replace the first comma it encounters in the reversed string. Then, reverse the string with the comma removed and you are done!</p>

<pre><code>string = 'something, is, comma,'
reverse_string = string[::-1] # Reverse the String
reverse_string = reverse_string.replace(',', "", 1) # Remove the first comma
string = reverse_string[::-1] # Reverse the string again to create original
print(string)
</code></pre>

python python-2.7 python-3.x