Python Operation % not working? - python

I cant seem to get this working, cant someone point me in the right direction? If i put the the values without promting it works buut when i do this i get error.
username1 = raw_input('Enter Username:\n')
password = raw_input('Enter Password:\n')
r = requests.get("https://linktoasp.net/",auth=HttpNtlmAuth("domain\\%s",password),cookies=jar) % (username1)
Error:
Traceback (most recent call last): File "attend_punch.py", line 32,
in
r = requests.get("https://linktoasp.netserver/homeportal/default.aspx",auth=HttpNtlmAuth("domain\\%r",password),cookies=jar)
% (username1) TypeError: unsupported operand type(s) for %:
'Response' and 'str'

You could try this instead
auth = HttpNtlmAuth("domain\\%s" % username1, password), cookies = jar)

What you probably want is:
r = requests.get(
"https://linktoasp.net/",
auth=HttpNtlmAuth("domain\\%s" % username1,password),cookies=jar)
In order to do string interpolation with %, the % and the value need to immediately follow the string:
"domain\\%s" % username1
rather than just coming later in the line:
HttpNtlmAuth("domain\\%s", ...) % username1

The % symbol can have 2 meanings in Python:
The modulo operator which will give you the remainder of the division of an int by the other. That is usually used for 2 numbers.
The string formatting operator which comes after a string to replace the placeholders with actual values. That's what you want, but you are not placing it right after the string, so Python interprets it as the modulo operator, and since it's not defined for any object (only for int usually), raises that exception.

Related

Beautiful Soup web scraping and working with integers

I have the following code, using BeautifulSoup and Python to webscrape (and subsequently work out a percentage) pertaining to some coronavirus stats:
url = "https://www.worldometers.info/coronavirus/"
req = requests.get(url)
bsObj = BeautifulSoup(req.text, "html.parser")
data = bsObj.find_all("div",class_ = "maincounter-number")
totalcases=data[0].text.strip()
recovered=data[2].text.strip()
print(totalcases+3)
percentagerecovered=recovered/totalcases*100
The issue I am having is in producing the required value for the variable percentagerecovered.
I want to be working with integers, but the above didn't work, so I tried:
percentagecovered=int(recovered)/int(totalcases)*100 but it gave this error:
File "E:\webscraper\webscraper\webscraper.py", line 17, in <module>
percentagerecovered=int(recovered)/int(totalcases)*100
ValueError: invalid literal for int() with base 10: '6,175,537'
However, when I removed the casting, and tried to just print to see the value it gave a different error, that I am struggling to understand.
I changed it to:
totalcases=data[0].text.strip()
recovered=data[2].text.strip()
print(totalcases+3)
percentagerecovered=recovered/totalcases*100
ERROR
File "webscraper.py", line 16, in <module>
print(totalcases+3)
TypeError: can only concatenate str (not "int") to str
I simply want to obtain those strings using the split method and then work with them assuming they are integers.
Currently, when I pass them (without casting) it doesn't display anything on the page...but when I do cast turning them into int, i get errors. What am I doing wrong?
I also tried:
totalcases=int(totalcases)
recovered=int(recovered)
but this produced a further error:
File "webscraper.py", line 17, in <module>
totalcases=int(totalcases)
ValueError: invalid literal for int() with base 10: '11,018,642'
I also tried this: (stripping the comma) as suggested below in the comments:
totalcases=data[0].text.strip()
recovered=data[2].text.strip()
totalcases=totalcases.strip(",")
totalcases=int(totalcases)
recovered=recovered.strip(",")
recovered=int(recovered)
percentagerecovered=recovered/totalcases*100
ERROR:
totalcases=int(totalcases)
ValueError: invalid literal for int() with base 10: '11,018,684'
I note solutions like the function below (which I haven't tried) yet but they seem unnecessarily complex for what I'm trying to do. What is the best and easiest/most elegant solution.
This seems along the right lines, but still produces an error:
int(totalcases.replace(',', ''))
int(recovered.replace(',', ''))
ERROR:
File "webscraper.py", line 25, in <module>
percentagerecovered=recovered/totalcases*100
TypeError: unsupported operand type(s) for /: 'str' and 'str'
i wrote this little function that return to you a number, so you can increase it or do what ever you want
def str_to_int(text=None):
if text == None:
print('no text')
else:
text = text.split(',')
num = int(''.join(text))
return num
For example you have the number of totalcases: '11,018,642', so you do this:
totalcases = str_to_int('11,018,642')
Now you can do totalcases*100 or anything else with it
Another simple way to do it:
totalcases= int(data[0].text.strip().replace(',',''))
recovered = int(data[2].text.strip().replace(',',''))

Error appears when attempting to create a map with folium in Python

My assignment is to create an html file of a map. The data has already been given to us. However, when I try to execute my code, I get two errors:
"TypeError: 'str' object cannot be interpreted as an integer"
and
"KeyError: 'Latitude'"
this is the code that I've written:
import folium
import pandas as pd
cuny = pd.read_csv('datafile.csv')
print (cuny)
mapCUNY = folium.Map(location=[40.768731, -73.964915])
for index,row in cuny.iterrows():
lat = row["Latitude"]
lon = row["Longitude"]
name = row["TIME"]
newMarker = folium.Marker([lat,lon], popup=name)
newMarker.add_to(mapCUNY)
out = input('name: ')
mapCUNY.save(outfile = 'out.html')
When I run it, I get all the data in the python shell and then those two errors mentioned above pop up.
Something must have gone wrong, and I'll admit I'm not at all good with this stuff. Could anyone let me know if they spot error(s) or know what I've done wrong?
Generally, "TypeError: 'str' object cannot be interpreted as an integer" can happen when you try to use a string as an integer.
For example:
num_string = "2"
num = num_string+1 # This fails with type error, because num is a string
num = int(num_string) + 1 # This does not fail because num is cast to int
A key error means that the key you are requesting does not exist. Perhaps there is no latitude key, or its misspelled/incorrect capitalization.

odd TypeError: 'int' object is not iterable

so i was coding some problems in python in this page
https://www.codewars.com/kata/airport-arrivals-slash-departures-number-1/train/python
the code work fine on my computer but when i update it, i came across this bug.
note that its python 3.4.3
def flap_display(lines, rotors):
baseString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ?!##&()|<>.:=-+*/0123456789"
res = []
baseLen = len(baseString)
lineLen = len(lines)
sLen = len(rotors)
carrier = 0
for item in range(0 , sLen):
if (item < lineLen):
carrier =carrier + rotors[item]
tmp = baseString.index(lines[item])
tmp = tmp + carrier
tmp = tmp % baseLen
res.append( baseString[tmp] )
resS = ''.join(res)
return resS
print (flap_display("CAT", [1,13,27]))
all the website gave me is this:
Traceback:
in
in flap_display
TypeError: unsupported operand type(s) for +: 'int' and 'list'
Now i want to know if my code is incorrect or its just the site being buggy.
Problem is solved! Thank to mr.kuro
sum requires an iterable: a sequence of items, such as a list. You gave it a single integer. If you want to add up all the integers in rotors, you can do that outside of a loop, with
carrier = sum(rotors)
More to your code, just add up the items you wanted:
carrier = sum(rotors[:lineLen])
This adds the first lineLen elements of rotors, allowing you to get rid of that pesky if statement.
Can you adapt the rest of the loop logic to take proper advantage of that?
Thr traceback should be like below:
Traceback (most recent call last):
File "test1.py", line 17, in
print (flap_display("CAT", [1,13,27]))
File "test1.py", line 10, in flap_display
carrier =carrier + sum(rotors[item])
TypeError: 'int' object is not iterable
And, as the traceback says, in line
carrier =carrier + sum(rotors[item])
rotors[item] will apparently be an int, so you can't call sum on it, hence the Error.
Replace the above line with:
carrier = carrier + rotors[item]
Or, just skip the loop, and do:
carrier = sum(rotors)
It should be okay now.

Binary To String Conversion

I'm relatively new to python and I'm trying to design a program that takes an input of Binary Data and Converts it to a String of Text. I have the following so far but keep getting the following error: TypeError: unsupported operand type(s) for &: 'str' and 'int' Can anyone see where I'm going wrong? And, if so, advise how to fix it?
a = int(input("please enter the binary you want to convert: "))
for str in a:
g = [~(chr(str)&~240)|(e&~240)]
f = 86
e = 231
d = bin(chr(str))
b = (str)
j=(b)
print(j)
There is quite a lot wrong with what you're doing; I'm not sure how you get the error you claim to have, given the other errors in the posted code. In order of reading the function:
Don't call your own variables str, it prevents you from accessing the built-in of the same name. Also, that variable either isn't a str, or causes a TypeError on chr(str).
You can't iterate over an integer for x in y:; this is also a TypeError.
(The error you report) chr(str) returns a string of length one. This is not a valid operand type for &, hence TypeError.
Another operand, e, has not yet been defined, so that will be a NameError.
Irrespective of that, you never use g again anyway.
Or f - what's that even for?
Now e is defined!
bin(chr(str)) will never work - again, chr returns a string, and bin takes a number as an argument.
b = (str) works, but the parentheses are redundant.
Same with j = (b), which is also not indented far enough to be in the loop.
Neither is print(j).
It is not clear what you are trying to achieve, exactly. If you gave example inputs (what format is the "Binary Data"?) and outputs (and what "String of Text" do you want to get?) along with your actual code and the full error traceback this might be easier.
Edit
With the information provided in your comment, it appears that you are trying to reverse these operations:
a = input("please enter the text you want to hide: ")
for ch in a:
## b = (ch) # this still doesn't do anything!
c = ord(ch)
## d = bin(c) # and d is never used
## e = 231 # e is only used to calculate g
f = 86
## g = (((c&240) >> 4)|(e&240)) # which is also never used
h = (((c&15)|(f&240)))
j = bin(h)
print(j)
This produces, for example (a == 'foo'):
0b1010110
0b1011111
0b1011111
However, to convert the input '0b1010110' to an integer, you need to supply int with the appropriate base:
>>> int('0b1010110', 2)
86
and you can't iterate over the integer. I think you want something like:
data = input("please enter the binary you want to convert: ")
for j in data.split():
h = int(j, 2)
...
where the input would be e.g. '0b1010110 0b1011111 0b1011111', or just do one at a time:
h = int(input(...), 2)
Note that, as the function is reversed, you will have to define f before trying to go back through the bitwise operation.

Python integer issues

EDIT: SOLVED--SOURCE CODE HERE: http://matthewdowney20.blogspot.com/2011/09/source-code-for-roku-remote-hack.html
thanks in advance for reading and possibly answering this. So I have a slice of code that looks like this (the commands Down() Select() and Up() are all predefined):
def c1(row):
row_down = row
row_up = row
while row_down > '1':
Down()
row_down = row_down - 1
time.sleep(250)
Select()
time.sleep(.250)
while row_up > '1':
Up()
row_up = row_up - 1
time.sleep(250)
So when I run this with either c1('3') or c1(3) (not jut 3, any number does this) it stops responding, no error or anything, but it executes the first Down() command, and it doesnt seem to get past the row_down = row_down - 1 . So i figure maybe it is stuck on time.sleep(.250), because it isnt executing the Select(), so if i remove time.sleep(.250) from the code i get an error like this:
Traceback (most recent call last):
File "test.py", line 338, in <module>
c1('3')
File "test.py", line 206, in c1
row_down = row_down - 1
TypeError: unsupported operand type(s) for -: 'str' and 'int'
this code snippet is part of a larger program designed for controlling the roku player from a computer, and so far everything has worked but this, which is to automate the typing in the search field, so that you do not have to continually scroll until you find a letter and select. c1(row) would be column 1 row x, if any of you would like the source code for the program over all, i would be happy to send it out. Anyway thanks for listening.
Perhaps you meant
while row_down > 1:
(note 1 is written without quotes). If so, call c1 with c1(3) not c1('3').
Also, in CPython (version 2, but not version 3) integers are comparable to strings, but the answer is not what you might expect:
3 > '1'
# False
When comparing any integer to any string, the integer is always less than string because (believe it or not!) i (as in integer) comes before s (as in string) in the alphabet.
As TokenMacGuy has already pointed out, addition of integers with strings raises a TypeError:
'3' - 1
# TypeError: unsupported operand type(s) for +: 'int' and 'str'
This might explain the error you are seeing when calling c1('3').
>>> x = raw_input('enter a number: ')
enter a number: 5
>>> x
'5'
>>> type(x)
<type 'str'>
>>> x + 5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>> type(int(x))
<type 'int'>
>>> int(x) + 5
10
>>>
(if you're using python3, use input instead of raw_input)
I suspect that the loop is running with out error because you can subtract from a character to change it: "b - 1 = a". (read edit) It also doesn't error is because, like Marcelo Cantos said in his comment, the first time.sleep is for 250 seconds, not .250 seconds. The error when you remove the time.sleep might be coming up when you subtract past the the ASCII character range since it runs through the loop a lot quicker without the time.sleep.
I hope that helps!
Edit: Actually, I think what I said works in C or something. In python, it doesn't work. The other stuff I said might shed some light though!

Categories