Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python unsupported operand type(s) for +: 'float' and 'str

Tags:

python

excel

wmi

I'm writing a short script where I plan on getting some information about the host PC and write it to an excel workbook. I'm still learning stuff so it's nothing fancy. I get all the data I need and can write in most of the stuff. I can't seem to get one thing work though. When trying the below code:

hardwareSheet.write("B7", usage + "%")

I can print out the "usage" variable only but when I add +"%" I keep getting the following error:

TypeError: unsupported operand type(s) for +: 'float' and 'str'

I'm using xlsxwriter library to crate and write excel. hardwareSheet.write is a command allowing me to write data into sheet named hardware. Here's how I got "usage" variable:

cpuInfo = wmi.Win32_Processor()[0]
usage = float(cpuInfo.LoadPercentage)

If I didn't parse cpuInfo.LoadPercentage to a float it would be a string. I googled this and read that I need to parse the str into a float so I did so.Any ideas what could be wrong?

like image 357
davidb Avatar asked Mar 16 '26 15:03

davidb


2 Answers

you can't add floats and strings in python. usage is a float. "%" is a string.

you should do something like:

str(usage) + '%'
like image 84
acushner Avatar answered Mar 18 '26 04:03

acushner


This is one more option to get the same output.

'{0}%'.format(usage)
like image 40
Tabaene Haque Avatar answered Mar 18 '26 05:03

Tabaene Haque



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!