1

I am using python 2.7 and i have a problem that i haven't encountered before, when i print a certain string and then a variable on the same line the variable is printed over the string. e.g. the script is coded like so print 'IP Rating = ', ipRating and the output in command prompt will be 'IP20ating = '. I have no idea why this is happening but i have the same code for various variables and string in the same script and they all come out as expected, i have tried renaming the variable and changing the string but there is still no difference, has anybody encoutered this error before or have any ideas why this might be happening? i can post the code if requested. Many thanks :)

EDIT Here is the code - I know i may have repeated myself a few times and there are unneccessary library's in there but the way i work is by importing all libraries i might need and then removing unnecessary code at the end.

from bs4 import BeautifulSoup as Soup
from bs4 import BeautifulSoup
from urllib import urlopen
import webbrowser
import httplib
import urllib2
import urllib
import string
import mylib
import xlrd
import glob
import xlwt
import bs4
import sys
import os
import re

print '\nStarting Web Search'
found = False
while found == False:
    excelFile = "F:\\len\\web sheets completed\\csv formatted\\imported\\re-imported\\Import Corrections\\saxby web spreadsheet.xls"
    try:
        inFi = xlrd.open_workbook(excelFile)
        found = True
    except IOError: 
        print 'File not found.' 
inFi = xlrd.open_workbook(excelFile)
inWS = inFi.sheet_by_index(0)
headers = mylib.getHeader(inWS)
supplyHead = mylib.findHeader('Supplier Part Ref', headers)
saxbeginurl = "http://www.saxbylighting.com/index.php?pg=search&ser="
badLink = "index.php?pg=search&ser=10180&next=0"
resLink = "http://www.saxbylighting.com/images/ProductImages/Zoomed/"
overCount = 0
for t in range(524,534):
    projection = 0
    ipRating = 0
    diameter = 0
    width = 0
    weight = 0
    length = 0
    height = 0
    i = 0
    w = 0
    l = 0
    h = 0
    d = 0
    p = 0
    x = 0
    iP = 0
    wei = 0
    imgStock = str(inWS.cell(t, supplyHead).value.encode('latin-1'))
    overCount = overCount + 1
    print '\n',imgStock
    if imgStock == '3TRAWI':
        url = 'http://www.saxbylighting.com/index.php?pg=details&prod=53'
    elif imgStock == '10313':
        url = 'http://www.saxbylighting.com/index.php?pg=details&prod=204'
    else:
        url = saxbeginurl + imgStock
    html_page = urllib2.urlopen(url)
    soup = BeautifulSoup(html_page)
    img_tags = soup.find_all("img")
    the_image_tag = soup.find("img", src='/images/dhl_logo.png')
    try:
        for dataSheet in soup.find('div',{'class':'panes'}):
            #print dataSheet, ' -- ', str(i)
            i = i + 1
            if i == 4:
                reqData = str(dataSheet).split('<img', 1)[0]
                first_Data = reqData.replace('<br/>','\n')
                second_Data = first_Data.replace('<b>','')
                third_Data = second_Data.replace('</b>','')
                fourth_Data = third_Data.replace(':',': ')
                dataList = fourth_Data.split('\n')
                #print dataList
                for information in dataList:
                    if 'Weight' in dataList[wei]:
                        pre_Weight = dataList[wei]
                        sec_weight = str(pre_Weight).replace('Weight :','')
                        weight = sec_weight.replace(' ','')
                    wei += 1
                    if 'IP' in dataList[iP]:
                        ipRating = str(dataList[iP])
                    iP += 1
        for product_Dimensions in dataList:
            if 'Product dimensions :' in dataList[x]:
                #print dataList[x]
                dimensionList = str(dataList[x]).replace('mm','mm:')
                #print dimensionList
                prelim_Dimensions = dimensionList.replace('Product dimensions :','')
                first_Dimensions = prelim_Dimensions.replace('cm','0mm')
                sec_Dimensions = first_Dimensions.replace('  ',' ')
                third_Dimensions = sec_Dimensions.strip()
                dimenList = third_Dimensions.split('mm:')
                #print dimenList
                for project in dimenList:
                    if 'Proj' in dimenList[p]:
                        pre_pro = str(dimenList[p]).replace('Proj','')
                        sec_pro = pre_pro.replace(':','')
                        thro_pro = sec_pro.replace(' ','')
                        projection = thro_pro
                    elif p == len(dimenList):
                        print 'Projection not found'
                    p += 1
                for diamet in dimenList:
                    if 'dia' in dimenList[d]:
                        pre_dia = str(dimenList[d]).replace('dia','')
                        sec_dia = pre_dia.replace(':','')
                        third_dia = sec_dia.replace(' ','')
                        diameter = third_dia
                    elif d == len(dimenList):
                        print 'Diameter not found'
                    d += 1
                for heig in dimenList:
                    if 'H:' in dimenList[h]:
                        pre_hei = str(dimenList[h]).replace('H','')
                        sec_hei = pre_hei.replace(':','')
                        third_hei = sec_hei.replace(' ','')
                        height = third_hei
                    elif h == len(dimenList):
                        print 'Height not found'
                    h += 1
                for lent in dimenList:
                    if 'L:' in dimenList[l]:
                        pre_leng = str(dimenList[l]).replace('L','')
                        sec_leng = pre_leng.replace(':','')
                        third_leng = sec_leng.replace(' ','')
                        length = third_leng
                    elif l == len(dimenList):
                        print 'Length not found'
                    l += 1
                for wid in dimenList:
                    if 'W:' in dimenList[w]:
                        pre_wid = str(dimenList[w]).replace('W','')
                        sec_wid = pre_wid.replace(':','')
                        third_wid = sec_wid.replace(' ','')
                        width = third_wid
                    elif w == len(dimenList):
                        print 'Width not found'
                    w += 1
            x += 1
        print 'IP Rating = ', ipRating
        print 'Weight = ', weight
        print 'Projection = ', projection, 'mm'
        print 'Diameter = ',diameter, 'mm'
        print 'Length = ',length, 'mm'
        print 'Height = ',height, 'mm'
        print 'Width = ',width, 'mm'
    except TypeError:
        print 'Type Error... skipping this product and carrying on.'

Here is an example output

IP44ating =
Weight =  .51KGS
Projection =  35 mm
Diameter =  0 mm
Length =  0 mm
Height =  90 mm
Width =  120 mm
8
  • 2
    yes code is requested, don't hesitate Commented Mar 11, 2014 at 12:12
  • Please post the code, and you could give this a try: print 'IP Rating = ', str(ipRating) Commented Mar 11, 2014 at 12:15
  • so you are saying that ipRating variable has the value 20, but when printed you get 'IP20ating = '.. right?? Commented Mar 11, 2014 at 12:16
  • theres the code,@Trygve the variable has already been formatted as a string, would reformatting it make a difference? and @Srivatsan thats exactly what happens except the ipRating variable is not always 20 Commented Mar 11, 2014 at 12:21
  • what happens if you print "IP Rating = {}".format(ipRating) Commented Mar 11, 2014 at 12:23

2 Answers 2

2

I strongly suspect that your data ipRating that you think is IP20 is actually \rIP20. That is: that you have a stray 0x13 carriage return character in there at the start of the variable. The carriage return character is moving the print position to the start of the line and then the variable is overwriting what you printed before.

You can test whether this is the problem by adding the line:

ipRating = ipRating.replace("\r", "")

before your print statement.

Sign up to request clarification or add additional context in comments.

2 Comments

I'll try this now and let you know the output
Good. You should try to work out where the stray character is coming from, however, rather than simply papering over the cracks.
0

This is the proper way to do what you're doing.

print('IP Rating = %s' % ipRating)

or

print('IP Rating = %d' % ipRating)

That is just one example from all the print statements you have at the end of your code.

If you're putting a string variable in print, use a %s or otherwise use a %d. If you have any more questions just ask.

8 Comments

he is using Python 2.7
This was done on Python 2.7 guys. It supports function based printing as well.
If you are going to suggest changing to the print function, wouldn't it also make sense to change to the format function? print('IP Rating = {0}".format(ipRating))
@Remolten Same output, thanks for the advice and the help though
@CasualDemon same output, damn this is frustrating haha
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.