What is the most elegant way to reverse the process of Python's str.format on replacing arguments by position?
For example for the following
textpattern = 'Please move {0} to {1}'
mystring = 'Please move a to b'
a deformat function :
mystring.deformat(textpattern)
will return the list ['a', 'b']. The variable textpattern is being entered by the user and then dynamically fetched from the DB.
The closest thing I found is a question about scnaf in Python but that's slightly different.
You're looking for the package parse which is described as: parse() is the opposite of format().
Related
Using Binance Futures API I am trying to get a proper form of my position regarding cryptocurrencies.
Using the code
from binance_f import RequestClient
request_client = RequestClient(api_key= my_key, secret_key=my_secet_key)
result = request_client.get_position()
I get the following result
[{"symbol":"BTCUSDT","positionAmt":"0.000","entryPrice":"0.00000","markPrice":"5455.13008723","unRealizedProfit":"0.00000000","liquidationPrice":"0","leverage":"20","maxNotionalValue":"5000000","marginType":"cross","isolatedMargin":"0.00000000","isAutoAddMargin":"false"}]
The type command indicates it is a list, however adding at the end of the code print(result) yields:
[<binance_f.model.position.Position object at 0x1135cb670>]
Which is baffling because it seems not to be the list (in fact, debugging it indicates object of type Position). Using PrintMix.print_data(result) yields:
data number 0 :
entryPrice:0.0
isAutoAddMargin:True
isolatedMargin:0.0
json_parse:<function Position.json_parse at 0x1165af820>
leverage:20.0
liquidationPrice:0.0
marginType:cross
markPrice:5442.28502271
maxNotionalValue:5000000.0
positionAmt:0.0
symbol:BTCUSDT
unrealizedProfit:0.0
Now it seems like a JSON format... But it is a list. I am confused - any ideas how I can convert result to a proper DataFrame? So that columns are Symbol, PositionAmt, entryPrice, etc.
Thanks!
Your main question remains as you wrote on the header you should not be confused. In your case you have a list of Position object, you can see the structure of Position in the GitHub of this library
Anyway to answer the question please use the following:
df = pd.DataFrame([t.__dict__ for t in result])
For more options and information please read the great answers on this question
Good Luck!
you can use that
df = pd.DataFrame([t.__dict__ for t in result])
klines=df.values.tolist()
open = [float(entry[1]) for entry in klines]
high = [float(entry[2]) for entry in klines]
low = [float(entry[3]) for entry in klines]
close = [float(entry[4]) for entry in klines]
So this is my first question on the forum and I hope I am doing it correct.
General question: How can I ensure that python does not return any errors when writing a script that allows the user to input values of different datatypes depending on the context or parameter they want to change?
More specific: I am new to python and want to write a script that allows users of The Foundry's Nuke to change values on multiple nodes of the same class at once. Depending on whether the desired parameter to change is a checkbox('bool'), and RGBA input ('4 floats')... the input has to be of a different type. Searching the forum I found that the type can be checked by type() function and compared in an if statement with the isinstance() function. I guess I could work with that, but the type of e.g. a Gradenode's multiply knob returns type 'AColor_Knob'. I expected something like float. And comparing it in an isinstance() does not give me a match regardless of the datatype I am comparing to.
Mainscript so far:
nukescripts.clear_selection_recursive()
userInput = nuke.getInput('Which type of nodes would you like to select? (!!!first char has to be capitalized!!!)',
'Shuffle')
matchingNodes = []
for each in nuke.allNodes():
if each.Class() == userInput:
matchingNodes.append(each)
else:
pass
for i in matchingNodes:
i.setSelected(True)
nuke.message(str(len(
matchingNodes)) + ' matching Nodes have been found and are now selected! (if 0 there either is no node of this type or misspelling caused an error!)')
userInput_2 = nuke.getInput('Which parameter of these nodes would you like to change? \n' +
'(!!!correct spelling can be found out by hovering over parameter in Properties Pane!!!)',
'postage_stamp')
userInput_3 = nuke.getInput('To what do you want to change the specified parameter? \n' +
'(allowed input depends on parameter type (e.g. string, int, boolean(True/False)))', 'True')
for item in matchingNodes:
item.knob(userInput_2).setValue(userInput_3)
How I checked the datatypes so far:
selected = nuke.selectedNode()
knobsel = selected.knob('multiply')
print(type(knobsel))
#if type(knobsel) == bool:
if isinstance(knobsel, (str,bool,int,float,list)):
print('match')
else:
print('no match')
You can call a TCL command with nuke.tcl(). In TCL, everything is a string, so type is irrelevant (in some commands).
p = nuke.Panel('Property Changer')
p.addSingleLineInput('class', '')
p.addSingleLineInput('knob', '')
p.addSingleLineInput('value', '')
p.show()
node_class = p.value('class')
knob_name = p.value('knob')
knob_value = p.value('value')
for node in nuke.allNodes(node_class):
tcl_exp = 'knob root.{0}.{1} "{2}"'.format(node.fullName(),knob_name,knob_value)
print tcl_exp
nuke.tcl(tcl_exp)
That should answer your question. There are many ways to approach what you're trying to do - if you want to keep it all in python, you can do type checking on the value of the knob. For example:
b = nuke.nodes.Blur()
print type(b.knob('size').value()).__name__
This creates a Blur node and prints the string value of the type. Although I don't recommend this route, you can use that to convert the value:
example = '1.5'
print type(example)
exec('new = {}(example)'.format('float'))
print type(new)
An alternative route to go down might be building yourself a custom lookup table for knob types and expected values.
Edit:
TCL Nuke Commands:
http://www.nukepedia.com/reference/Tcl/group__tcl__builtin.html#gaa15297a217f60952810c34b494bdf83d
If you press X in the nuke Node Graph or go to File > Comp Script Command, you can select TCL and run:
knob root.node_name.knob_name knob_value
Example:
knob root.Grade1.white "0 3.5 2.1 1"
This will set values for the named knob.
I'm newbie for python 2.7. I would like to create some function that knows which are variables in the given probability notation.
For example: Given a probability P(A,B,C|D,E,F) as string input. The function should return a list of events ['A','B','C'] and a list of sample spaces ['D','E','F']. If it is impossible to return two lists in the same time. Returning a list of two lists would be fine.
In summary:
Input:
somefunction('P(A,B,C|D,E,F)')
Expected output: [['A','B','C'],['D','E','F']]
Thank you in advance
A simple brute-force implementation. As #fjarri pointed out if you want to do anything more complex you might need a parser (like PyParser) or at least some regular expressions.
def somefunction(str):
str = str.strip()[str.index("(")+1:-1]
left, right = str.split("|")
return [left.split(","), right.split(",")]
This question already has answers here:
How to construct a std::string with embedded values, i.e. "string interpolation"?
(8 answers)
Closed 2 years ago.
I am rewriting our application using wxWidgets. One of the goals is to replace our old approach to the localized strings. Another possible goal is to embed the Python interpreter to the application -- but only later. Anyway, it would be nice any C/C++ code or library capable of Python-like string formatting that uses the curly braces.
If you do not know Python, here is the doc for its format function. You can find the reference to the Format Specification Mini-Language inside, and the Format examples. Some extract from the doc... (The >>> is a prompt of the interactive Python mode, the line below shows the result of the call. Python uses single or double quotes as a string delimiter):
>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated
'abracadabra'
I would also like to use the Python formatting with the named placeholders (instead of numeric indices). In Python, the str.format_map(mapping) method of strings is used where the mapping is of the map<string, some_type> like type. Say, my_dictionary contains mapping like:
"name" --> "Guido"
"country" --> "Netherlands"
Having a template string like below, I would like to get the result...
wxString template("{name} was born in {country}.");
wxString result(format_map(s, my_dictionary));
// the result should contain...
// "Guido was born in Netherlands."
Do you know any avaliable C or C++ code capable of that, or do I have to write my own?
Thanks for your time and experience,
Petr
Yes. The fmt library uses format string syntax based on Python's str.format. It supports most of the formatting options of str.format including named arguments. Here's an example:
std::string s = fmt::format("{0}{1}{0}", "abra", "cad");
// s == "abracadabra"
Disclaimer: I'm the author of this library.
I'm trying to use numbers as my dict key. Is there anyway to initiate the dictionary using dict() method?
This works
mydict = { '100':'hundred', '200':'two hundred'}
This doesn't work?
mydict = dict( 100='hundred' )
The error says 'keyword can't be an expression' and I couldn't find any solution.
Thank you.
I can't understand your question exactly, but you mentioned to use number as dict key right? you just directly initiate it using integer instead string like this..
a = {1:'one',100:'hundered'}
print a
{1: 'one', 100: 'hundrered'}
No, it mist be a valid python identifier, so it cannot start with a number.
You can read where i found it at here in the part about dict
https://docs.python.org/2/library/stdtypes.html#typesmapping
Like the comment above says you can use an int, since dictionaries just hash the string and you get an int anyways, in the case of an int it just hashes to itself. But it doesnt work with dict ()
On that page it shows you can do
mydict = dict (zip ([1], ["one"]))
Which is kinda ugly imo, but seems to get the job done
To use the dict method you need to feed it a list or tuple of lists or tuples.
>>> dict([(100, 'hundred'), (200, 'two hundred')])
{200: 'two hundred', 100: 'hundred'}