I'm working to create a tuple in Python in the following way:
tuple = (the_schema['fields'][i]['name'],the_schema['fields'][i]['type'])
and am getting the output ('stn', 'str').
My desired output is ('stn', str), where the second element of the tuple doesn't have the single quotes.
When I print (the_schema['fields'][i]['type']), I get str as desired. The issue, as I understand, is that Python automatically formats the tuple with quotations. How can I remove the quotation? I have tried the .replace() and .strip() methods, as well as something similar to ",".join([str(s) for s in list(k)]).
From python 3.6 on, you can use f-strings to create strings using variables, and that is quite easy to do.
Here, for your output you could use:
string_tuple = f"('{the_schema['fields'][i]['name']}', {the_schema['fields'][i]['type']})"
Related
I'm using a format() in python and I want to use a variable pokablelio so that the person could choose how many numbers to output after the dot. When I try to put the variable alone after the comma it outputs: ValueError: Invalid format specifier. I tried replacing some characters or making the whole string in a parentheses but that didn't work.
Right now I'm wondering: Can I even use a variable as a string to put it in format's place?
(note: The machine should have a "'.10f'" string in the variable)
Error and the code
It is possible to use variables as part of the format specifier, just include them inside additional curly braces:
>>> n_places = 10
>>> f'{1.23:.{n_places}f}'
'1.2300000000'
I have an xpath in the following format
xpath='//*[#id="peoplegrid"]/div[5]/div[1]/a'
I want to pass a string to the first div in the x path in the following manner
x=[1,2,3,4,5]
for i in x:
xpath='//*[#id="peoplegrid"]/div[',+str(i),']/div[1]/a'
print(xpath)
However when I run this, it states that bad operand type for unary +: 'str'
How can I pass a string to this xpath
Following is the full piece of code I am working on
x=[1,2,3,4]
for i in x:
python_button=driver.find_element_by_xpath('//*[#id="peoplegrid"]/div,'+[str(x)]+'/div[1]/a')
python_button.click()
driver.execute_script("window.history.go(-1)")
You're missing the second +. Try something like this.
xpath='//*[#id="peoplegrid"]/div['+str(i)+']/div[1]/a'
I cannot update #Steven's answer with such a subtle (less than 6 character) change, so I've created my own answer.
What you need is the following:
xpath='//*[#id="peoplegrid"]/div['+str(i)+']/div[1]/a'
As you can tell, between my answer and #Steven's answer, mine does not include the commas within the first div portion of the XPATH. For your purposes, it is unnecessary and invalid to place the commas in the string. Commas are typically used in print statements to prevent newlines from being appended to the output.
EDIT: In regards to the change to the original post and the comments therein, concatenating a list to a string is also invalid. Merely use an interpreter and try compiling the code, and a TypeError: must be str, not list will be thrown. This makes sense, since you cannot append a list directly to a str; however, if the contents of the list are strings, or can be converted to strings, then you can concatenate these. See here for an explanation of string concatentation in Python.
It's best to avoid constructing the XPath expression by string concatenation. Disadvantages:
(a) you need to worry about escaping strings that contain special characters
(b) you need to REALLY worry about it if there's any possibility of people inserting bad strings maliciously (XPath injection attacks)
(c) you have to compile the expression each time it's used.
I don't know the Python API you are using, but most XPath APIs allow you to compile an expression containing variables (eg. '//[#id="peoplegrid"]/div[$param]/div[1]/a') and then bind a value to the variable separately. If you can do this then it's much preferable and avoids the above disadvantages.
As said in the title of the thread.
Also I tried using eval() for these lists I'll be inputting, but these lists contain string elements and other (sub-?) lists, e.g:
[Pacific, [-45,30,25], [120,59, 15]]
When providing such input eval() responds perfectly fine for numbers-only lists but when applied to strings sends back a NameError for these string elements saying they are not defined.
you need to be inputting your strings within quotations, ie,
["Pacific", [-45,30,25], [120,59, 15]]
when you input it just as Pacific, python's eval() function will look for a variable named Pacific, hence the NameError you have been getting
Your original input string is perfectly valid YAML string, which is a safe, powerful and -at least in my view- easy way to serialize and de-serialize data structures. In order to read (or save) YAML strings you might want to get PyYAML:
sudo pip install pyyaml
Then, you can perfectly run the following code in order to read your data into Python:
from yaml import load
pacific = load('[Pacific, [-45,30,25], [120,59, 15]]')
I have a list of strings and a command I'd like to run with Popen. The command takes the strings as input arguments.
How can I easily add the entire list...
list=['asdf','qwer','zxcv',...]
...as comma separated input shown below:
Popen(['cmd','asdf','qwer','zxcv',...])
I won't be able to do this because it won't convert list to str implicitly:
Popen(['cmd',list])
Nor this, because it simply won't allow for spaces within a string:
Popen(['cmd',' '.join(list)])
Is there an alternative?
I do not want to use the 'shell=True' option.
You can do the following to create a new list from two (or more) separate lists.
['cmd'] + list
This creates a new list for you with the contents of both. As you mentioned, the syntax looks and does exactly as you expect, which is adding two lists together.
Note: I would also like to warn that you shouldn't use list as a variable name. Since this means you are shadowing the built-in list type. Which could cause unforeseen problems later.
Which of these Python string interpolations is proper (not a trick question)?
'%s' % my_string
'%s' % (my_string)
'%s' % (my_string, )
If it varies by version, please summarize.
Old format
The first one is the most common one. The third has unnecessary parenthesis and doesn't help the legibility if you've only one object you want to use in your format-string. The second is just plain silly, because that's not even a tuple.
New format
Nowadays starting with Python 2.6, there's a new and recommended way of formatting strings using the .format-method:
In your case you would use:
'{}'.format(my_string)
The advantage of the new format-syntax are that you enter more advanced formattings in the format string.
All three of these are equivalent.
The first two are exactly equivalent, in fact. Putting brackets around something does not make it a tuple: putting a comma after it does that. So the second one evaluates to the first.
The third is also valid: using a tuple is the normal way of doing string substitution, but as a special case Python allows a single value if there is only one element to be substituted.