Right now I have the method below, it works perfectly fine but I want to change part of the self.wait_for_element(....) to instead use %s rather than calling str(counter)
> def gather_recent_visited_courses_in_content_switcher(self):
hover_courses = self.browser.find_elements_by_xpath("//div[contains(#class, 'recent-content flyout-closed')]")
course_list = []
counter = 1
for course in hover_courses:
self.hover_over(course)
# Change the below to %s
self.wait_for_element("//div[contains(#class, 'fly-wrapper recent-content-trigger')][" + str(counter) + "]//div[contains(#class, 'recent-content-info')]", 'Course list not found')
course_display_name = course.find_element_by_xpath("//div[contains(#class, 'recent-content-info')]").text
course_list.append(str(course_display_name))
counter += 1
return course_list
Currently I keep getting errors when replacing it with [%s], like below
> self.wait_for_element("//div[contains(#class, 'fly-wrapper recent-content-trigger')][%s]//div[contains(#class, 'recent-content-info')]", 'Course list not found' %(counter))
Does anyone have any ideas on how to get this to work properly? So far, I keep getting 'not all arguments converted during string formatting' errors
The reason why using %s isn't working is because you are setting the placeholder value in the second string argument, and not the first string as you have intended.
With the first argument:
"//div[contains(#class, ...)][%s]//div[... 'recent-content-info')]"
Python can't find the proper value to replace %s with in the first string argument. So, that will raise an error.
As for the second argument:
'Course list not found' % (counter)
You are passing a value to the string but the string cannot be formatted to use the passed value because the string doesn't have placeholder, %s. So, that'll raise an error too.
To fix that, just format the first string argument. It'll look like this:
"//div[contains(#class, '...')][%s]//div[..., 'recent-content-info')]" % counter
Alternatively, you can use .format(). This the new style of string formatting. Using %s is considered to be the old style[1].
"//div[contains(#class, '...')][{}]//div[..., 'recent-co...')]".format(counter)
NOTE: Strings have been redacted to make things easier to read.
References
[1] - https://pyformat.info/
Related
I have to variables one="{}{}{}T{}:{}:{}" and two='2021,-10,-28,05,40,33' When i try to use print(one.format(two)) i am getting errors. IndexError: Replacement index 1 out of range for positional args tuple. guessing it is because the two variable is being seen as a string.
So I switched and tried to do the *args method.
for item in two:
item = str(item)
data[item] = ''
result = template.format(*data)
However if I switch two='2021,-10,-28,00,00,00.478' it fails because a dictionary is unique. so how do i get the first method to work or is there a better solution.
You should split the two into list and then unpack it with *
one="{}{}{}T{}:{}:{}"
two='2021,-10,-28,05,40,33'
print(one.format(*two.split(','))) # 2021-10-28T05:40:33
I have list with one item in it, then I try to dismantle, & rebuild it.
Not really sure if it is the 'right' way, but for now it will do.
I tried using replace \ substitute, other means of manipulating the list, but it didn't go too far, so this is what I came up with:
This is the list I get : alias_account = ['account-12345']
I then use this code to remove the [' in the front , and '] from the back.
NAME = ('%s' % alias_account).split(',')
for x in NAME:
key = x.split("-")[0]
value = x.split("-")[1]
alias_account = value[:-2]
alias_account1 = key[2:]
alias_account = ('%s-%s') % (alias_account1, alias_account)
This works beautifully when running print alias_account.
The problem starts when I have a list that have ['acc-ount-12345'] or ['account']
So my question is, how to include all of the possibilities?
Should I use try\except with other split options?
or is there more fancy split options ?
To access a single list element, you can index its position in square brackets:
alias_account[0]
To hide the quotes marking the result as a string, you can use print():
print(alias_account[0])
cur=connection.cursor()
def fillDoctors(key_bodyloc,proportion):
bodyloc_specialty_query="select distinct Speciality from body_speciality where body_location in (%s) "
#cur.execute(bodyloc_specialty_query)
data1=([key_bodyloc])
#print(bodyloc_specialty_query,data)
cur.execute(bodyloc_specialty_query,data1)
results=cur.fetchall()
specialities=[x[0] for x in results]
condition=""
for speciality in specialities:
print(str(speciality))
condition=condition+"'%"+speciality+"%'"+" or Speciality like "
#print(speciality)
#print(condition)
specialty_doctors_query="select DoctorName,Speciality,ClinicName from Doctors where Speciality like %s limit %s"
data2=([condition,proportion])
print(specialty_doctors_query,data2)
cur.execute(specialty_doctors_query,data2)
final=cur.fetchall()
print(final)
The line final=cur.fetchall() returns an empty tuple in each iteration. I've verified that the table Doctors isn't empty and the code works fine when the 'condition' is hard-coded. The code is supposed to print the doctor details for each speciality. Can anyone tell me why this is happening ?
Seems to me you are not passing your data1 into bodyloc_specialty_query properly when calling cur.execute(bodyloc_specialty_query,data1) and it causes the problem.
The syntax of string injection in Python is the following:
str1 = "some string %s" % "other string"
Instead of this way of adding a string to a string, use Pythons format builtin function:
str1 = "some string {str2}".format(str2="other_string").
But make sure that your str2 is a string or convertable to string.
I can see your data1 is a list, not str. You should convert it to str first. Good luck.
The whole point of passing in parameters to the execute method is that they get escaped. So, your condition is treated as a single string, rather than a series of parameters joined by SQL. Also, you can't use a parameter for the LIMIT value.
You need to build up some SQL and placeholders by interpolation, then just pass the values.
like = "speciality LIKE %%%s%%"
condition = like + (" OR {}".format(like)) * len(specialities)
query = "select DoctorName,Speciality,ClinicName from Doctors where {} LIMIT {}".format(condition, proportion)
cursor.execute(query, specialities)
for speciality in specialities:
condition=condition+"'%"+speciality+"%'"+" or Speciality like "
I am using Python 2.7 and Django 1.6.11 for my project and I want iterating to get a list of params with code like this:
for idx in range(1, int(number_unit_orders) + 1):
is_edit = request.POST.get('edit_%s'.format(str(idx)))
# Do something with is_edit
But the is_edit is always None although edit_1 and so on are set in the request object. But the code block below works(use string concatenation):
for idx in range(1, int(number_unit_orders) + 1):
is_edit = request.POST.get('edit_' + str(idx))
# Do something with is_edit
Wonder why this is the case.
'edit_%s'.format(str(idx))
Is mixing up two different types of formatting
You need to choose one of them and stick to it
'edit_%s' % str(idx) # 'edit_%d % idx
'test_{}'.format(idx)
The reason you're getting none is because you're trying to get an object that doesn't exist, it is actually currently looking up the exact string of edit_%s
In format method you don't use % but {}.
Please rewrite your line with this method to:
is_edit = request.POST.get('edit_{}'.format(idx))
Also explicit str is not needed.
Format doesn't work like that. Your code should be:
'edit_{0}'.format(str(idx))
When running the following code I would like to be able to store the returned values in a variable as a string. However when I run the code it will return the first name from the database in this format
[(u'Kiefer',)]
What would I need to change in order to just return a clean string? I was thinking I could use strip although I have never used it on a tuple (not even sure if you can) but I was hoping there is a more elegant way. Also I am using the sqlite3 module.
def search_db(self,ID,FName,LName):
#try:
FName +='%'
LName += '%'
self.cur.execute(("""SELECT FirstName FROM members WHERE FirstName LIKE '%s'\
AND LastName LIKE '%s'""") % (FName, LName))
value = (self.cur.fetchall())
print(value)
#except:
#print('failed')
cla = Database()
cla.search_db(1,'K','D')
You need to access the first element of the list, which is the tuple, then the first element of the tuple, so:
value[0][0]