How to call dynamicly string operations in Python? [duplicate] - python

This question already has answers here:
How do I execute a string containing Python code in Python?
(14 answers)
Closed last month.
//func_to_exec parameter is coming from database dynamically.
func_to_exec='split("\|")[0].split(",")[1]'
pl='mancity,manunited,arsenal|2|3|4|5'
is there anyway to call
pl.func_to_exec
I saw exec and eval functions are only for integers. I cant find any solution for strings.
Thx for suggestions.

You can use the exec function for that:
pl = 'mancity,manunited,arsenal|2|3|4|5'
func_to_exec = 'split("\|")[0].split(",")[1]'
exec(f'result = pl.{func_to_exec}')
print(result) # Output: 'manunited'

Related

Is it possible run a string in Python [duplicate]

This question already has answers here:
How do I execute a string containing Python code in Python?
(14 answers)
Closed 1 year ago.
Is it possible to run a String text?
Example:
str = "print(2+4)"
Something(str)
Output:
6
Basically turning a string into code, and then running it.
Use exec as it can dynamically execute code of python programs.
strr = "print(2+4)"
exec(strr)
>> 6
I will not recommend you to use exec because:
When you give your users the liberty to execute any piece of code with the Python exec() function, you give them a way to bend the rules.
What if you have access to the os module in your session and they borrow a command from that to run? Say you have imported os in your code.
Sure is, looks like your "Something" should be exec.
str = "print(2+4)"
exec(str)
Check out this previous question for more info:
How do I execute a string containing Python code in Python?

Identifying line breaks anywhere in a dataframe [duplicate]

This question already has answers here:
How can I check for a new line in string in Python 3.x?
(4 answers)
Closed 1 year ago.
Looking for ways in which I can run an equivalent of a 'find' in Python in order to be able to identify line breaks.
I have tried using this but it didn't return any results unexpectedly:
df[df.isin(['\n']).any(axis=1)]
The str accessor has a function to search for substrings.
df["colA"].str.contains(r"\n")
Use it in conjunction with apply to get your solution.
df.apply(lambda s: s.str.contains(r"\n"))
If you want a pd.DataFrame as result, use:
df1 = testdf[testdf['B'].str.contains('\n')]
Another solution would be with iloc and np.where:
testdf.iloc[np.where(testdf['B'].str.contains('\n', regex=False))]

EASY How do I use the count() and capitalize() function? [duplicate]

This question already has answers here:
Why doesn't calling a string method (such as .replace or .strip) modify (mutate) the string?
(3 answers)
Closed 3 years ago.
I am new to Python and stack overflow. How do I use the count and capitalize functions for my strings? The app I am learning from appears to have this mixed up because it dosen't work in vscode.
It seems like the capitalize function call is ignored. What am I doing wrong? If someone could tell me how to use the count function as well I have the same problem. The app I learn from is called Programminz.
This is Python 3
practice = "CaPITalIzE mE proPerLy"
practice.capitalize()
print(practice)
string_name.capitalize()
string_name: It is the name of string of
whose first character we want
to capitalize.
Try to use :
string = "CaPITalIzE mE proPerLy"
capitalized_string = string.capitalize()
print('Old String: ', string)
print('Capitalized String:', capitalized_string)

How to call various strings without using %s? [duplicate]

This question already has answers here:
Type Error: Format Requires Mapping
(2 answers)
Closed 3 years ago.
text1="Python"
text2="with me"
print("Study %(language)s" %{'language':text1})
This works. But I am wondering whether it is using dictionary to call string?
print("Study %(language)s %(with whom)" %({'language':text1},{'with whom':text2}))
But it doesn't work. How can I fix it?
The error says 'format requires a mapping'
It would have worked, if you noticed that:
you've forgotten to put an s after %(with whom) --> %(with whom)s,
and instead of this %({'language':text1},{'with whom':text2}) --> %{'language':text1,'with whom':text2}
so the line would be like this:
print("Study %(language)s %(with whom)s" %{'language':text1,'with whom':text2})

Python, can someone explain why the return statement only prints the first object? [duplicate]

This question already has answers here:
What does return mean in Python? [closed]
(2 answers)
Why is "None" printed after my function's output?
(7 answers)
Python: Why "return" won´t print out all list elements in a simple for loop and "print" will do it?
(4 answers)
Closed 5 years ago.
I have been practising python and have a small question. I am working with DNA sequences and so I simply wanted to make a small function that just returned the record.ids.
from Bio import AlignIO
my_alignment = Align.IO.read("multipleseqfile.fa","fasta")
def get_id_names(alignment):
for record in alignment:
return record.id
print get_id_names(my_alignment)
I had done a for loop before that prints the names nicely but I wanted to improve my script and make these exercises into functions. However, when I use this function, it only returns the first record id (and there is a list of 30-40). I switched the return record.id to print record.id, and it does print all the names but then I get a None at the end of the output. Not sure what is going on here?

Categories