My goal here is trying to match the list of strings against list of ints:
For example my list of strings: wholelookup[uniprotID] = [A177T,I126T,M418T].
My list of ints: lookup[uniprotID] = [177,126,418].
If there is a match then I would like to print the token in wholelookup.
Here is what i have so far but it didn't print anything as the result:
for item in lookup[uniprotID]:
for names in wholelookup[uniprotID]:
if start <= item <= end and re.match(item, names) :
item, start, end = map(int, (item, start, end))
print names
match tries to match from the beginning. Also: you do not want to match a 1 to for instance a321a .
You could use 're.match(r'\w'+str(item)+r'\w', names)' instead of re.match(item, names)
Or use re.search:
re.search(r'\d+',names).group(0)==item
Why use a regex at all?
Assuming start and end are already ints and item is a string, try this:
for item in lookup[uniprotID]:
if start <= int(item) <= end: continue
for names in wholelookup[uniprotID]:
if str(item) in names :
print names
Related
I have a list that contains some strings , I want to add some predefined values before every string in a list but the value at the end of the iteration should be different
Here is the list
lst = ['USER_INVITE','USER_LEAVE','GIVEAWAY_START','GIVEAWAY_EDIT','USER_INVITE','USER_LEAVE']
the expected output is
<:878677713269968896:909470525108154399> USER_INVITE
<:878677713269968896:909470525108154399> USER_LEAVE
<:878677713269968896:909470525108154399> GIVEAWAY_START
<:878677713269968896:909470525108154399> GIVEAWAY_EDIT
<:878677713269968896:909470525108154399> USER_INVITE
<:878677686350934027:910454682219085834> USER_LEAVE
here you can see the value before USER_LEAVE is different than others
I can simply do something like this to put these values before strings without a loop
logs = '<:878677713269968896:909470525108154399>\n'.join(map(str,keys[I]))
maybe iteration will help in this case by doing something else at the end of the loop
Using iteration, and some control flow logic around identifying the last item in the list, this can be done as follows:
output_str = ""
for i, item in enumerate(lst):
if i == len(lst) - 1: # Logic for identifying the last element
prefix = '<:878677686350934027:910454682219085834>'
else: # If not the last element in the list, do this:
prefix = '<:878677713269968896:909470525108154399>'
output_str += f'{prefix} {item}\n'
output_str = ""
for item in lst[:-1]:
output_str += f'<:878677686350934027:910454682219085834> {item}\n'
output_str += f'<:878677713269968896:909470525108154399> {lst[-1]}'
You can just work on every key but the last and then combine the output at the end.
a = "\n".join('<:878677713269968896:909470525108154399>' + key for key in lst[:-1])
b = '<:878677686350934027:910454682219085834>' + lst[-1]
a + b
'<:878677713269968896:909470525108154399>USER_INVITE\n<:878677713269968896:909470525108154399>USER_LEAVE\n<:878677713269968896:909470525108154399>GIVEAWAY_START\n<:878677713269968896:909470525108154399>GIVEAWAY_EDIT\n<:878677713269968896:909470525108154399>USER_INVITE<:878677686350934027:910454682219085834>USER_LEAVE'
New to python-
I need to create a "while" loop that searches for the position of a certain string in a text file.
All the characters in the file have been set to integers (x = len(all)), so now I need a loop to search for the index/position of a certain string.
This is where I'm at right now:
string = 'found'
index = 0
while index < x:
if ????
Then it should print out something like
String found between (startIndex) and (endIndex)
You can use the .find() function:
string = "found"
x = "I found the index"
index = x.find(string)
end = index + len(string)
print(index, end)
2, 7
Python has a built-in function called index that provides this functionality:
string = "found"
with open("FILE", "r") as f:
for i,j in f.readlines():
if string in j:
foo = f.index(string)
print(f"String found at line {i+1} between ({foo}) and ({foo + len(string)})")
break
Given a list
n = ['4276-4279', 'I69-I71', 'V104-V112', '11528']
From the list above, I want to match the string with hyphens and increase the numeric or alphanumeric value to a given range. So far I could only match the value using re:
p = re.compile('([\d]|[A-Z\d]{1,})[\-]')
Expected output:
['4276', '4277', '4278', '4279', 'I69', 'I70', 'I71', 'V104', 'V105', 'V106', 'V107', 'V108', 'V109', 'V110', 'V111', 'V112', '11528']
You can process each element in your list, seeing if it matches the pattern
^([A-Z]*)(\d+)-\1(\d+)$
i.e. an optional letter, some digits, a hyphen (-), the letter repeated if it was present and finally some more digits.
If it does, you can generate a range from the 2nd and 3rd groups, and prepend the first group to each value generated from that range:
import re
lst = ['4276-4279', 'I69-I71', 'V104-V112', '11528']
new = []
for l in lst:
m = re.match(r'^([A-Z]*)(\d+)-\1(\d+)$', l)
if m:
new += [m.group(1) + str(i) for i in range(int(m.group(2)), int(m.group(3))+1)]
else:
new += [l]
print(new)
Output:
['4276', '4277', '4278', '4279', 'I69', 'I70', 'I71', 'V104', 'V105', 'V106', 'V107', 'V108', 'V109', 'V110', 'V111', 'V112', '11528']
import re
n = ['4276-4279', 'I69-I71', 'V104-V112', '11528']
big_list=[]
for item in n:
print(item)
if '-' in item:
part1,part2=item.split("-")
if part1.isnumeric() and part2.isnumeric():
big_list.extend([x for x in range(int(part1),int(part2))])
continue
if part1.isalnum() and part2.isalnum():
list1=re.findall(r"[^\W\d_]+|\d+", part1)
list2=re.findall(r"[^\W\d_]+|\d+", part2)
print(list1,list2)
temp_list=[]
for i in range(int(list1[1]),int(list2[1])):
temp_list.append(list1[0]+str(i))
big_list.extend(temp_list)
else:
if item.isnumeric():
big_list.append(int(item))
else:
big_list.extend(item)
print(big_list)
This code worked for me for your input.
Please try and tell me if it works.
How to replace characters in a string which we know the exact indexes in python?
Ex : name = "ABCDEFGH"
I need to change all odd index positions characters into '$' character.
name = "A$C$E$G$"
(Considered indexes bigin from 0 )
Also '$'.join(s[::2])
Just takes even letters, casts them to a list of chars and then interleaves $
''.join(['$' if i in idx else s[i] for i in range(len(s))])
works for any index array idx
You can use enumerate to loop over the string and get the indices in each iteration then based your logic you can keep the proper elements :
>>> ''.join([j if i%2==0 else '$' for i,j in enumerate(name)])
'A$C$E$G$'
name = "ABCDEFGH"
nameL = list(name)
for i in range(len(nameL)):
if i%2==1:
nameL[i] = '$'
name = ''.join(nameL)
print(name)
You can reference string elements by index and form a new string. Something like this should work:
startingstring = 'mylittlestring'
nstr = ''
for i in range(0,len(startingstring)):
if i % 2 == 0:
nstr += startingstring[i]
else:
nstr += '$'
Then do with nstr as you like.
what i want to do is take a string and for each character make the ordinal value 1 more from the value it has.
myinput=input("Message : ")
mylist =list(myinput) #convert to list in order to take each character
for character in mylist:
mylist[character]+=ord(mylist[character])+1
print(character)
The problem is with the "ord(mylist[character])+1"
Thank you!
Probably you are looking for the next:
>>> m = raw_input('Message:')
Message:asdf
>>> ''.join(chr(ord(c) + 1) for c in m)
'bteg'
Notes:
use raw_input when you need to get string input from a user;
ord convert character to integer, chr - vise versa;
... for c in m syntax is a generator expression. It is also used for list comprehension.
Three problems here. First, you're mixing up list indices and list elements. Second, you didn't convert back to a character (I'm assuming you want characters, not numbers). Third, you're adding to the existing value.
One way:
for i range(len(mylist)):
mylist[i] = chr(ord(mylist[i])+1)
Another way:
for i, character in enumerate(mylist):
mylist[i] = chr(ord(character)+1)
Instead of
for character in mylist:
mylist[character]+=ord(mylist[character])+1
(where character is a list index and therefore invalid), you probably want:
mylist = [ord(character) + 1 for character in mylist]
Or a Counter.
You can do like this
def ordsum(astring, tablesize):
sum = 0
for num in range(len(astring)):
sum = sum + ord(astring[num])
return sum
myinput = input() # use raw_input() in Python 2
myinput = map(lambda ch: chr(ord(ch) + 1), myinput)
# or list comp.
myinput = [chr(ord(ch) + 1) for ch in myinput]
You can iterate directly over a string, you do not have to make it a list first. If your end goal is to have a new string, you can do this:
myinput=input("Message : ")
result = []
for character in myinput:
result.append( chr( ord( character ) + 1 )
mynewstring = ' '.join(result)