简体   繁体   English

Python-将变量打印在字符串上

[英]Python - Variable being printed over string

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. 我正在使用python 2.7,我遇到了一个以前从未遇到过的问题,当我打印某个字符串然后在同一行上打印一个变量时,该变量会打印在字符串上。 eg the script is coded like so print 'IP Rating = ', ipRating and the output in command prompt will be 'IP20ating = ' . 例如,脚本的编码方式如下,因此print 'IP Rating = ', ipRating ,命令提示符下的输出将为'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

I strongly suspect that your data ipRating that you think is IP20 is actually \\rIP20 . 我强烈怀疑您认为IP20数据ipRating实际上是\\rIP20 That is: that you have a stray 0x13 carriage return character in there at the start of the variable. 也就是说:在变量的开头,您有一个错位的0x13回车符。 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. 在您的打印对帐单之前。

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. 这只是代码末尾所有print语句中的一个示例。

If you're putting a string variable in print, use a %s or otherwise use a %d. 如果要打印字符串变量,请使用%s或其他方式使用%d。 If you have any more questions just ask. 如果您还有其他问题,请提出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM