XdansLaFoule
XdansLaFoule

Reputation: 87

move a word to the end of the line using python

I'm parsing an HTML and I'm getting a string of Array that I'm trying to clean it and put in into pdf later. At this level, I would like to move all the words started by @X to the end of the line so I could have in the end all the @X aligned.

Hello World @Xabs
Hello World                                   @Xz
Hello World  @Xss
Hello World         @Xssa
Hello World       @Xqq
Hello World             @Xsasas

What I would like to have as an output :

Hello World                                        @Xabs
Hello World                                        @Xz
Hello World                                        @Xss
Hello World                                        @Xssa
Hello World                                        @Xqq
Hello World                                        @Xsaxs

Any ideas?

What I have so far:

# encoding=utf8 
import sys
reload(sys) 
#import from lxml import html 
from bs4 import BeautifulSoup as soup 
import re import codecs 
sys.setdefaultencoding('utf8') 

# Access to the local URL(Html file) f=codecs.open("C:\...\file.html", 'r') 
page = f.read() 
f.close() 

#html 
parsing page_soup = soup(page,"html.parser") 
tree = html.fromstring(page) # extract the important arrays of string 

a_s= page_soup.find_all("td", {"class" :"row_cell"})
for a in a_s:
    result = a.text.replace("@X","")
    print(final_result)

Upvotes: 3

Views: 585

Answers (2)

blue note
blue note

Reputation: 29081

There is no specific line-width concept in a string. If you want to align your text, print the first part with constant width

output = "{:50s} {}".format('preceding text', 'Xword')

Upvotes: 5

Chris
Chris

Reputation: 29742

Quite similar to @blue_note's answer, but making the entire solution more automatical:

import re

lines = ['Hello World @Xabs',
         'Hello World                                   @Xz',
         'Hello World  @Xss',
         'Hello World         @Xssa',
         'Hello World       @Xqq',
         'Hello World             @Xsasas']

aligned_lines = []
for line in lines:
    match = re.findall('@X\w+', line)[0]
    line = line.replace(match,'')
    aligned_lines.append('%-50s %s' % (line, match))

aligned_lines

['Hello World                                        @Xabs',
 'Hello World                                        @Xz',
 'Hello World                                        @Xss',
 'Hello World                                        @Xssa',
 'Hello World                                        @Xqq',
 'Hello World                                        @Xsasas']

Upvotes: 1

Related Questions