I'm new in python and I'm trying to concatenate an url with an integer but i get this error:
TypeError: cannot concatenate 'str' and 'int' objects*
My code looks like this:
for x in range(0,10):
url = "http:www.eluniversal.com.mx/minuto-x-minuto?seccion=All&page="+(x)
x +=1
Can someone help me?
Python is a dynamically strongly typed langauge. So it won't convert an integer to string when you try to concatenate them.
You have to either use string interpolation or explicitly convert it to an string.
url = "http:www.eluniversal.com.mx/minuto-x-minuto?seccion=All&page=%s" % x
url = "http:www.eluniversal.com.mx/minuto-x-minuto?seccion=All&page=" + str(x)
url = "http:www.eluniversal.com.mx/minuto-x-minuto?seccion=All&page="+str(x)
Add a "str" in front of your brackets and it will work. By doing this you can convert the int into a string.
url += str(x)
x+=1 has no effect.
Related
im having trouble figuring out the syntax to concatenate and cast to a string to following section of code
new_prod_list2 = list(map(lambda x:x str(['product_id'])) + x['product_category'] + x['product_name'] , products))
print(new_prod_list2)
Product_category and product_name concatenate, but when i try to concatenate product_id (which is a int) using str to convert it to a string, i keep getting errors.
Would anyone mind helping me with this problem, it would be greatly appreciated.
Bring the x that's right after the colon in the lambda expression into the str() call, so that the ['product_id'] item access gets invoked:
new_prod_list2 = list(map(lambda x: str(x['product_id']) + x['product_category'] + x['product_name'] , products))
And the more Pythonic way to do this would be to use list comprehension and string formatting:
new_prod_list2 = [f'{x["product_id"]}{x["product_category"]}{x["product_name"]}' for x in products]
I am currently working with JSON and Python and I have a problem.
When I write:
x = {}
x['red'] = {'name': "red"}
y = {}
y['red'] = {'p': 1}
z = x['red']['name'], y['red']['p']
print(z)
I get back:
('red', 1)
But I want it like:
red1
Without using
print(x['red']['name'], y['red']['p'])
Thanks for your help :)
When we resolve the variables in the line
z = x['red']['name'], y['red']['p']
we get this:
z = "red", 1
This is, in Python the same as writing:
z = ("red", 1)
This line defines a data-type called a "tuple". It is similar to a list. When you use print to write out the value of this variable, Python formats this as such and adds the parens.
If you want the string "red1" as output, you need to do some minor string processing. In your tuple, your first item is a string, the next is an integer. Those two are not directly concatenable in Python using +. You either need to convert (cast) the number first, or use a string formatting function:
Example 1 - Using str() to cast the number to string
z = x['red']['name'] + str(y['red']['p'])
Example 2 - Using simple string formatting
z = '%s%s' % (x['red']['name'], y['red']['p'])
Example 3 - Using f-strings
z = f"{x['red']['name']}{y['red']['p']}"
Just concatenate the string, easy:
z = y['red']['name'] + str(z['red']['p'])
print(z)
You need to call str() around z['red']['p'] because it's an integer. By converting it to a string, you can then concatenate the two strings into one string
When you type z = x['red']['name'], y['red']['p'] Python automatically takes it as tuple.
But you want this to be treated as string and get concatenated results.
for this you may use,
z = str(x['red']['name']) + str(y['red']['p'])
print(''.join(z)) does the trick.
Cheers
Demo: https://repl.it/repls/MinorRoyalTrace
Edit: use print(''.join(str(element) for element in z)) instead for handle str+ int
I've already applied the following code:
my1name = 'Alicia'
my2name = 'Shifflett'
yearP = '2019'
my1nameSpace = my1name + ''
print(my1name.isalnum())
print(my1name.isalnum())
print(yearP.isalnum())
The task wants me to apply isalnum() to the string my1name+my2name. I tried the following:
print(my1name+my2name.isalnum())
But I keep getting the error: TypeError: can only concatenate str (not "bool") to str
How do I type this out correctly to get it to work?
I am trying to loop through elements on the page and then get the text from the element. While getting the text, I am trying to strip a specific word "NEW" and then add it in the list.
Here is my code.
def test(self, cardname):
mylist = []
allrows = self.driver.find_elements_by_xpath("//*[contains(#id, 'scopes-pending-')]")
count = len(allrows)
for i in range(count):
rows = self.driver.find_element_by_id("scopes-" + cardname + "" + str(i) + "").text
if "NEW" in rows:
row_split = rows.strip('NEW')
mylist.append(row_split.text)
else:
mylist.append(rows.text)
return mylist
But I am getting this error
Exception: 'str' object has no attribute 'text'
I have tried a bunch of different ways but none of them are working. For example,
rows = self.driver.find_element_by_id("scopes-" + cardname + "" + i + "").text
which gives me the following error:
Exception: must be str, not int
It seems like I am missing something very small and need help figuring it out (still new to python). Any help is appreciated.
One thing you want to get right from the very beginning is to use descriptive variable names. This will help you and anyone else that has to read your code understand what you are trying to do.
I changed a few variable names using my best guess at what they were. Obviously feel free to change them to whatever makes sense if I guessed wrong.
mylist -> labelList
allrows -> rowLabels
rows -> rowLabel (singular since it's only one)
Removed some "extra" variables. I tend to not create a new variable if I'm not going to use it again. For example, count just holds len(allrows). You can remove count and just use len(allrows) in the only place it shows up, in the for loop.
Removed some extra ""s you had in your locator, e.g. ...cardname + "" + str(i) + "". The + "" + doesn't do anything here since you are just concatenating an empty string "" so I removed those.
rows.strip() will remove the string if the substring exists. If the substring doesn't exist, it just returns the entire string. Since this is the case, you don't need an if-else.
The below code is how I would write this.
def test(self, cardname):
labelList = []
allrows = self.driver.find_elements_by_xpath("//*[contains(#id, 'scopes-pending-')]")
for i in range(len(allrows)):
rowLabel = self.driver.find_element_by_id("scopes-" + cardname + str(i)).text
labelList.append(rowLabel.strip('NEW'))
return labelList
Caveat... I'm not a python programmer so there may be some more optimizations and ways to make this code more python-y than I have suggested.
As to the errors,
Exception: 'str' object has no attribute 'text'
row_split = rows.strip('NEW')
mylist.append(row_split.text)
In the above lines, row_split is a string and you are doing <string>.text which causes the error. .text can be used on a Web Element.
Exception: must be str, not int
rows = self.driver.find_element_by_id("scopes-" + cardname + "" + i + "").text
You fixed this one already. It's complaining that i is an int and not a string. str(i) fixes that.
Have you tried just appending row_split? If it's a str object, it likely is the text you're looking for (str in Python is the string object).
If you added the line you're getting the error on, that'd be helpful too.
My guess is that your first exception is from trying to get the text attribute from row_split from a string (I assume that the the text attribute returned from self.driver.find_element_by_id is of type str).
And then you get the second exception from trying to concatenate a str and an int (that'd be i). You were right to cast i to a str.
I want to calculate the average flow, but I have hard time converting string to float in python.
here is my code in notepad++:
import cookielib,urllib2,urllib,string
import cx_Oracle
import datetime
import string
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
total_flow = 0
count = 0
page = opener.open("http://cdec.water.ca.gov/cgi-progs/queryCSV?station_id=vns&sensor_num=20&dur_code=E&start_date=2016-04-14&end_date=2016-04-15&data_wish=View+CSV+Data")
for line in page:
a=line.split(',')
b = float(a)
count+=1
total_flow= total_flow+b[-1]
# here a=[date,time,flow]; so b[-1] is flow data
ave_flow = total_flow/count
print ave_flow
when I ran this script, I got the error message:
b=float(a)
type error: float() argument must be a string or a number
however, when I directly converted string to float in python, it worked. I don't know what was going on.
Here a is a list not a string. You should have another for loop to handle each element in the list.
a = line.split(',')
This returns a list. That's why you are getting an error.
a=line.split(',')
a is a list here, try something like:
b=float(a[0])
ok, I figured it out. there are some invisible symbol along with string in the list so i can't simply convert string to number.
i changed to
a=line.strip().split(",")
b=float(a[-1])
and it works.