How to remove only one instance of specified character in string - python

If I have a list of strings such as the following:
"apple.test.banana", "test.example","example.example.test".
Is there a way to return only "test.banana" and "example.test"?
I need to check and see if there are two dots, and if there are, return only the value described above.
I attempted to use:
string="apple.test.banana"
dot_count=0
for i in string:
if i==".":
dot_count=dot_count+1
if dot_count>1:
string.split(".")[1]
But this appears to only return the string "test".
Any advice would be greatly appreciated. Thank you.

You are completely right, except for the last line, which sould say '.'.join(string.split(".")[1:]).
Also, instead of the for loop, you can just use .count(): dot_count = string.count('.') (this doesn't affect anything, just makes your code easier to read)
So the program becomes:
string = "apple.test.banana"
dot_count = string.count('.')
if dot_count > 1:
print('.'.join(string.split(".")[1:]))
Which outputs: test.banana

Related

How to replace all T with U in an input string of DNA?

So, the task is quite simple. I just need to replace all "T"s with "U"s in an input string of DNA. I have written the following code:
def transcribe_dna_to_rna(s):
base_change = {"t":"U", "T":"U"}
replace = "".join([base_change(n,n) for n in s])
return replace.upper()
and for some reason, I get the following error code:
'dict' object is not callable
Why is it that my dictionary is not callable? What should I change in my code?
Thanks for any tips in advance!
To correctly convert DNA to RNA nucleotides in string s, use a combination of str.maketrans and str.translate, which replaces thymine to uracil while preserving the case. For example:
s = 'ACTGactgACTG'
s = s.translate(str.maketrans("tT", "uU"))
print(s)
# ACUGacugACUG
Note that in bioinformatics, case (lower or upper) is often important and should be preserved, so keeping both t -> u and T -> U is important. See, for example:
Uppercase vs lowercase letters in reference genome
SEE ALSO:
Character Translation using Python (like the tr command)
Note that there are specialized bioinformatics tools specifically for handling biological sequences.
For example, BioPython offers transcribe:
from Bio.Seq import Seq
my_seq = Seq('ACTGactgACTG')
my_seq = my_seq.transcribe()
print(my_seq)
# ACUGacugACUG
To install BioPython, use conda install biopython or conda create --name biopython biopython.
The syntax error tells you that base_change(n,n) looks like you are trying to use base_change as the name of a function, when in fact it is a dictionary.
I guess what you wanted to say was
def transcribe_dna_to_rna(s):
base_change = {"t":"U", "T":"U"}
replace = "".join([base_change.get(n, n) for n in s])
return replace.upper()
where the function is the .get(x, y) method of the dictionary, which returns the value for the key in x if it is present, and otherwise y (so in this case, return the original n if it's not in the dictionary).
But this is overcomplicating things; Python very easily lets you replace characters in strings.
def transcribe_dna_to_rna(s):
return s.upper().replace("T", "U")
(Stole the reordering to put the .upper() first from #norie's answer; thanks!)
If your real dictionary was much larger, your original attempt might make more sense, as long chains of .replace().replace().replace()... are unattractive and eventually inefficient when you have a lot of them.
In python 3, use str.translate:
dna = "ACTG"
rna = dna.translate(str.maketrans("T", "U")) # "ACUG"
Change s to upper and then do the replacement.
def transcribe_dna_to_rna(s):
return s.upper().replace("T", "U")

DataFrame Panda: if-elif.. if block is not picked up

CSV is formatted as:
Dataframe is:
I am trying to achieve a if conditions. But it executes the else block and outcomes are always "Value3".Where I am going wrong?
Add strip as given below:
def validate(row):
if row['TRANSACTION DESC'].strip()=='JWPFMAIN':
val="Value1"
elif row['TRANSACTION CD'].strip()=='':
val="Value2"
else:
val="Value3"
return val
dfwithcolumns['Status'] = dfwithcolumns.apply(validate, axis=1)
Try to use elif instead of the second if. Because then if the first one is true but the second if statement is false then the val would default to value3. Also make sure that for the second if statement that it is a space, because it could also be a '' empty string.

Best alternative to using if statement?

I am trying to break out of a bad habit of using if/else too frequently. I am new to how functions work and the proper way to call them but I am constantly researching the correct way to implement them with my code. The code that I am making is suppose to check for 3 different words and if the word is not in the input then the user will receive a statement that says "rejected" if the word is correct it will say "accepted". The issue that I am facing is getting my program to work correctly. So far I have set up my program to check each index of the word and if it matches the full word it will be marked as accepted. I am trying to figure out the correct way to add a rejected flag and to avoid the error that I recieve after running this program.
def checker():
q0 = input("enter word:")
if (q0[0]) +(q0[1]) == "if":
print ("accepted")
if (q0[0]) + (q0[1]) + (q0[2]) + q0[3] == "else":
print("accepted")
if(q0[0]) + (q0[1]) == "do":
print("accepted")
else:
print("rejected")
checker()
For this program, I am not going to use a dictionary so I can correctly challenge myself and implement this in an automata fashion. How can I implement this code without getting the string index out of range error. I tried to put break after my print statement but it doesn't work.
Thanks in advance to everyone. This is my first post so if I have made any mistakes in my post please let me know!
Here's an extensible one-liner for you:
def check():
q = input().strip()
acceptable = {'if', 'else', 'do'}
print('accepted' if q in acceptable else 'rejected')
The variable acceptable is set; a data structure which is very quick to check if something is inside of it. You can modify this set (or pass it to check as an argument!) to change the range of acceptable words without changing the control flow of the program (as you would in your original if/else implementation that you're laudably trying to move away from).
EDIT: I guess it's not strictly a 'one-liner'...
First, why do you access each character of the input string, then concatenate them again, then compare to a target string("if", "else", "do")?
Second, why do you use if statements repeatedly if matching either one of them will lead to the same result (print("accepted")?
Try this:
def checker():
q0 = input("enter word:")
if q0 in ["if", "else", "do"]:
print("accepted")
else:
print("rejected")
checker()
Now, you just compare a string q0 to another (each element of the list ["if", "else", "do"]). Also, the first hit in the list will make stop comparing anymore and will continue on to print "accepted".
++ Just to let you know why are you seeing "index out of range error", you are accessing each character of q0 without knowing how many there are. So if the user inputs a string like a, there's no q0[1] or q0[2], but you're asking your program to access it. Thus index out of range error.
You can do this with a for loop and one if statement if that is better for you. Simply put all the accepted values into a list and check if each word is in q0.
def checker():
q0 = input('enter word:')
for i in ['if', 'else', 'do']:
result = ('accepted' if i in q0 else 'rejected')
if result == 'accepted':
break
print(result)
you can do it as one liner with lambda function.
checker = lambda q: print("accepted" if q in ["elif", "if", "else"] else "rejected")
checker()
here is a sample
>>> checker = lambda q: print("accepted" if q in ["elif", "if", "else"] else
"rejected")
>>> checker("if")
accepted
>>> checker("fool")
rejected

TypeError: list indices must be integers, not str. Know the issue, not the answer

Unique situation, I know the problem, just dont know a solution.
import string
timefile = open('lasttimemultiple.txt','r+')#opens the file that contains the last time run
lasttime = timefile.read()#reads the last time file
items= int(2)
splitlines = string.split(lasttime,'\n')
print splitlines[items][0:2]
timefile.close() #closes last time
PullType = '00'
datapt = '01'
for items in splitlines:
if splitlines[items][0:2] == PullType:
datapt = splitlines[items]
else:
print ''
print datapt
I know my issue is I am using 'items' as the index I am calling versus an integer, but I don't know how to use a reference to work through the data without using an non-int variable name.
Any ideas how to achieve this?
Thanks
You should show the actual traceback. If you had, you would have seen that the error is in this line:
if splitlines[items][0:2] == PullType:
That's because items here has been redefined by the for loop in the line before. In a for loop in Python, the variable is not a counter, it is the actual item from that iteration. So, in the first iteration, items is the first element of splitlines, etc. So it is a string, not an integer. The fix is to use it directly:
if items[0:2] == PullType:
(Also, you should think about better variable names: that should be item, not items).

How to make an if statement using widget option values as conditions?

Let's say i have a this button:
tl.config(bd=0 ,image=photo1 ,width="100",height="100",command=lambda: functionPlus(tl))
The function is :
def functionPlus(button):
global turn
if (turn==1 or turn==3 or turn==5 or turn==7 or turn==9):
button.config(image=photo2,width="100",height="100")
turn +=1
elif (turn==2 or turn==4 or turn==6 or turn==8) :
button.config(image=photo3,width="100",height="100")
turn+=1
I would like to add an 'if' in the function, that would have as condition the image of the button. For exemple :
if button.config(image=photo2 == True) :
anotherFunction()
Thanks in advance.
First, never use the expression pattern something=something else == True!
Second, take a look at this related (but not duplicate) question.
As you can see there, the cget method will return the current value for an option. As this manual page mentions, cget is analogous to widget["option"].
So, to answer your question directly, the if condition you need would be along the lines of:
if button['image']==photo2:
anotherFunction()
I'm new here and couldn't comment. I hope I'm not flaunting SO policy by resorting to answering instead.
#Tersosauros
"First, never use the expression pattern something=something else ==
True!"
Where do you see this pattern and why should it be avoided? What could replace it? (I know you're a tersosaurus but "never use X" just seems TOO terse and uninformative).
#Arwan Credoz I know you got your answer but... If you simply want to check whether the value of "turn" is a an even/odd number and is within a given range, use a bounds check followed by modulus instead (maybe this is what #Tersosauros was hinting at?).
Also, the value of "turn" will always be incremented if it's within range(0,10) so there's no need to write "turn+=1" twice. If I've understood your intentions correctly, you could probably rewrite "functionPlus" to something like this and add Tersosaurus' addition where appropriate:
def functionPlus(button):
global turn
if 0 < turn < 10:
if turn % 2 == 0:
button.config(image=photo3,width="100",height="100")
else:
button.config(image=photo2,width="100",height="100")
turn += 1

Categories

Resources