I have a combo box on a form that I created. This combo box displays an ID and a name together. I am writing the contents of the combo box to a database. So far it writes correctly when I use this piece of code
self.ui.residentComboBox.currentText()
Now what I want to be able to do is pull only the ID from the combo box instead of the ID and the name together. Can anyone help?
If self.ui.residentComboBox.currentText() returns a string, and the ID is just the first word, you can do this:
self.ui.residentComboBox.currentText().split()[0]
which splits the string into a list of words (separated by whitespace) and then the [0] gives the first item in that list.
For example:
t = "3426523 askew chan"
print t.split()
#['3426523','askew','chan']
print t.split()[0]
#'3426523'
Related
I'm writing a webscrabing program and need to bulk search on FedEx, to do this I normally concatenate all my tracking numbers with "\n" between them to stand as an equivalent as pasting text from an excel column
issue is when I enter my string into their search box, it enters the number concatenated as if without the delimiter, so the search box only sees 1 long tracking number rather than multiple (lie if pasted from excel) any idea on how I can get the string formatted, or sent to the search box correctly?
this is what it looks like when I paste 2 tracking numbers 12345 and abcdefg:
and here's what it should look like:
here is my code for sending the string to the search box:
def fedex_bulk(tn_list):
# you can mostly ignore until the end of this function, all this is setup for the driver #
# all relevant formatting is in the creating of variable search_str #
driver = start_uc()
loaded = False
size=3
tn_list = [tn_list[i:i+size] if i+size <= len(tn_list) else tn_list[i:len(tn_list)] for i in range(0,len(tn_list),size)]
tn_dict = []
for sublist in tn_list:
tries = 0
### concatenate all tracking numbers with "\n" delimiter
search_str = ''
for tn in sublist:
search_str+=tn+'\n'
### loop until numbers searched or tried 4 times
while not loaded:
try:
if tries==4:
break
tries+=1
### refresh until loaded
driver.get("https://www.fedex.com/en-us/tracking.html")
page_loaded = False
while not page_loaded:
try:
inputform = driver.find_element(By.XPATH, "//input[#class='form-input__element ng-pristine ng-invalid ng-touched']")
page_loaded = True
except:
driver.refresh()
sleep(5)
### search_str sent to search box, formatted incorrectly
inputform.send_keys(search_str)
sleep(1)
driver.find_element(By.XPATH, "//button[#type = 'submit']").click()
thankyou in advance!
I think the problem here is as following:
Inside the for sublist in tn_list: loop you do adding a '\n' to each tracking number tn in the sublist so search_str is containing a list of tracking numbers concatenated with '\n' between them.
But inside the while not page_loaded: you are locating the first input field and then you are sending to it all that long string containing multiple tracking numbers.
The search input element on the page is probably limited to accept valid inputs only, so it just ignores all the '\n' signs.
On the other hand, you are not inserting your tracking numbers to other search field inputs as you presenting on the picture showing how it should look.
So, in order to make your code work as you want you will probably need to insert single tracking number each time or to insert them to different search input fields.
I am trying to use a text widget in tkinter to display the output of my code.
sequence = ("This peptide contains ", len(Peptide), "total residues", "\n")
text.insert("current", sequence)
this seems to work, except for that when it is printed, the
elements are separated by {}.
I would prefer for the output to not have these parenthesis, and read like: "This peptide contains 17 total residues". Is there a way to do this?
Thank you
It is because sequence is a tuple. Try changing it to
sequence = "This peptide contains {} total residues\n".format(len(Peptide))
I have some files that have "TITLE..." then have "JOURNAL..." followed directly afterward. The specific lines are varied and are not static per file. I am trying to pull all of the information that exists between "...TITLE..." and "...JOURNAL...". So far, I am able to only pull the line that contains "TITLE", but for some files, that spills onto the next line.
I deduced that I must use a=line.find("TITLE") and b=line.find("JOURNAL")
then set up a for loop of for i in range(a,b): which displays all of the numerical values of the strings from 698-768, but only displays the number instead of the string. How do I display the string? and how do I then, clean that up to not display "TITLE", "JOURNAL", and the whitespaces in between those two and the text I need? Thanks!
This is the one that displays the single line that "TITLE" exists on
def extract_title():
f=open("GenBank1.gb","r")
line=f.readline()
while line:
line=f.readline()
if "TITLE" in line:
line.strip("TITLE ")
print(line)
f.close()
extract_title()
This the the current block that displays all of thos enumbers in increasing order on seperate lines.
def extract_title():
f=open("GenBank1.gb","r")
line=f.read()
a=line.find("TITLE")
b=line.find("JOURNAL")
line.strip()
f.close()
if "TITLE" in line and "JOURNAL" in line:
for i in range(a,b):
print(i)
extract_title()
Currently, I have from 698-768 displayed like:
698
699
700
etc...
I want to first get them like, 698 699 700,
then convert them to their string value
then I want to understand how to strip the white spaces and the "TITLE" and "JOURNAL" values. Thanks!
I am not sure if I get what you want to achieve here but if I understood it correctly you have a string similar to this "TITLE 659 JOURNAL" and want to get the value in the middle ? If so you could use the slicing notation as such:
line = f.read()
a = line.find("TITLE") + 5 # Because find gives index of the start so we add length
b = line.find("JOURNAL")
value = line[a:b]
value = value.strip() # Strip whitespace
If we now were to return value or print it out we get:
'659'
Similar if you want to get the value after JOURNAL you could use slicing notation again:
idx = line.find("JOURNAL") + 7
value = line[idx:] # Start after JOURNAL till end of string
you don't need the loop. just use slicing:
line = 'fooTITLEspamJOURNAL'
start = line.find('TITLE') + 5 # 5 is len('TITLE')
end = line.find('JOURNAL')
print(line[start:end])
output
spam
another option is to split
print(line.split('TITLE')[1].split('JOURNAL')[0])
str.split() returns list. we use indexes to get the element we want.
in slow motion:
part2 = line.split('TITLE')[1]
title = part2.split('JOURNAL')[0]
print(title)
I am trying to create a text editor for python using tkinter. When the user highlights lines of text and presses tab, I want the program to add a tab in front of each line of selected text, similar to what Idle does. This is the function I have so far:
self.TextBox.bind('<KeyPress-Tab>', self.tabtext)
def tabtext(self, e):
try:
untabbed = self.TextBox.selection_get() # get selected text
lines = untabbed.split('\n') # splits into a list of lines
tabbed = ''
for i in range(len(lines)):
lines[i] = ' ' + lines[i] # adds tabs to each line
tabbed = '\n'.join(lines) # joins list with newline character
old = self.TextBox.get("1.0", tk.END) # gets old text
new = old.replace(untabbed, tabbed) # replaces all instances of highlighted
# text with new text
self.TextBox.delete('1.0', tk.END) # deletes old text
self.TextBox.insert(tkinter.END, new) # adds new text
return 'break' # prevents it from deletion
except:
return
This code works, however if the selected text appears in the text box more than once, it will add tabs to each instance of the selected code. Is there any way to resolve this, maybe involving finding the position of the selected text. Any help would be greatly appreciated.
You can just replace the selected code rather that deleting and re-inserting all of the text.
The first step is to get the index of the start of the line for the selection:
index = self.TextBox.index("sel.first linestart")
Next, delete all of the lines in the selection:
self.TextBox.delete("sel.first linestart", "sel.last lineend")
Finally, insert the new text
self.TextBox.insert(index, tabbed)
Alternate method
Though, if all you're doing is inserting tags, you don't need to delete-and-replace. You can also just insert a tab for every line in the selected range. All you have to do is iterate over the lines. It would look something like this:
def tabtext(self, e):
last = self.TextBox.index("sel.last linestart")
index = self.TextBox.index("sel.first linestart")
while self.TextBox.compare(index,"<=", last):
self.TextBox.insert(index, " ")
index = self.TextBox.index("%s + 1 line" % index)
return "break"
I cannot figure this out, but say I have a depth-3 array of strings called "text".
How can it be that in the following code:
print "FIRST"
for gate in text[1:]:
print "GATE"
for text in gate:
print "TEXT"
for entry in text:
print "ENTRY"
print what
print "SECOND"
for gate in text[1:]:
print "GATE"
for text in gate:
print "TEXT"
for entry in text:
print "ENTRY"
print what
I get different output for each loop.
"First"
FIRST
GATE
TEXT
ENTRY
א
ENTRY
מחברת אל"ף
ENTRY
אחל לבאר לשון יהודית, להעמיד כל מלה כפי שאת, יש מלה רבת פנים ולא יתבונן המשכיל יסודותיה, כי אם במהות ענינה אשר סביבותיה למרבית פניה, כי המלה מושכת והולכת עד אשר מתחלקת ממראה אחד עד חמשה עשר פנים, על כן יש מלה אשר הענין ימשכנה ויורה עליה וילמד על גזרתה. ויש מלה אשר היא מושכת הענין ומבארת הפתרון ושכל סודו, וכה הוא פתרון הלשון ופשר המלים לפי מחלקותיהם ותוצאותיהם.
TEXT
ENTRY
אב.
"Second"
SECOND
GATE
TEXT
ENTRY
מ
TEXT
ENTRY
ת
TEXT
ENTRY
ח
TEXT
ENTRY
ל
TEXT
ENTRY
Each Loop is coded exactly the same and yet I get different output. How is this possible?
for loops "leak" variables. You might expect gate, text, and entry to be scoped to their respective loops, but they're actually global. So, at the end of this loop
for text in gate:
The value of text has been altered, which affects the next loop.
Here's a more minimal example:
x = 'abc'
for x in x:
print x,
# output: "a b c"
for x in x:
print x,
# output: "c"
(If being able to run the same code twice and get the same result is the kind of thing that you find valuable, Python might not be the right choice of language for you. There are plenty of lovely languages that do have this property.)
text has been modified. Before the SECOND loop, text has its value taken from the last iteration of for text in gate: ...
You should consider renaming the inner loop variable to something different.