subprocess.Popen('lccomm','n=RACK')
//i want something like this
subprocess.Popen('lccomm','n=input()')
Starting for Python 3.6, there is a convenient feature called f-string
subprocess.Popen('lccomm', f'n={input()}')
For Python 3.5-, there are also multiple string formatting options. For example, as mentioned by Ruzihm in his helpful comment
subprocess.Popen('lccomm', 'n=%s' % input())
arg = input()
subprocess.Popen('lccomm','n={}'.format(arg))
Related
A basic math question in the python code I tried multiple variation from the original code in the class with no results. Such as print('23+7'). It won't do the calculation in any form it is written.
If you want your output to be in the form of a string, you can also use f-strings (python ≥3.6): print(f'{23+7}')
Try print(23+7), -> '' or "" define a string in python.
I would like to know how could I format this string:
"){e<=2}"
This string is inside a function, so I would like to asign the number to a function parameter to change it whenever I want.
I tried:
"){e<={0}}".format(number)
But it is not working,
Could anybody give me some advice?
Thanks in advance
Double the braces which do not correspond to the format placeholder...
"){{e<={0}}}".format(number)
You could also use an f-string, if using Python 3.6 or above.
f"){{e<={number}}}"
An old-school version for this:
"){e<=%d}" % (number)
'){e<=2}'
I am quite new to python and i struck an issue wherein, I am dynamically retrieving a string from a dictionary which looks like this
files="eputilities/epbalancing_alb/referenced assemblies/model/cv6_xmltypemodel_xp2.cs"
I am unable to to perform any actions on this particular file as it is reading the path as 2 different strings
eputilities/epbalancing_alb/referenced and assemblies/model/cv6_xmltypemodel_xp2.cs
as there is a space between referenced and assemblies.
I wanted to know how to convert this to raw_string (ignore the space, but still keep the space between the two and consider it as one string)
I'm not able to figure this out although several comments where there on the web.
Please do help.
Thanks
From the comments to the other answer, I understand that you want to execute some external tool and pass a parameter (a filename) to it. This parameter, however, has spaces in it.
I'd propose to approaches; definitely, I'd use subprocess, not os.system.
import subprocess
# Option 1
subprocess.call([path_to_executable, parameter])
# Option 2
subprocess.call("%s \"%s\"" % (path_to_executable, parameter), shell=True)
For me, both worked, please check if they work yor you as well.
Explanations:
Option 1 takes a list of strings, where the first string has to be the path to the executable and all others are interpreted as command line arguments. As subprocess.call knows about each of these entities, it properly calls the external so that it understand thatparameter` is to be interpreted as one string with spaces - and not as two or more parameters.
Option 2 is different. With the keyword-argument shell=True we tell subprocess.call to execute the call through a shell, i.e., the first positional argument is "interpreted as if it was typed like this in a shell". But now, we have to prepare this string accordingly. So what would you do if you had to type a filename with spaces as a parameter? You'd put it between double quotes. This is what I do here.
Standard string building in python works like this
'%s foo %s'%(str_val_1, str_val_2)
So if I'm understanding you right either have a list of two strings or two different string variables.
For the prior do this:
' '.join(list)
For the latter do this:
'%s %s'%(string_1, string_2)
Stupid question with (for sure) simple answer...
I am using configparser to read some strings from a file. When the string has the '%' symbol ($%& for example) it complains:
ConfigParser.InterpolationSyntaxError: '%' must be followed by '%' or '(', found: "%&'"
Anybody familiar with this?
Thanks!
If you don't want environment variable substitution, then use RawConfigParser, not ConfigParser.
Write two %:
V = ('%%', 'MHz', 'GHz')
result:
('%', 'MHz', 'GHz')
By default, ConfigParser has interpolation of values enabled. That means that you can use variables inside your properties files.
Since Python 3.2, you can disable interpolation in the constructor:
configParser = configparser.ConfigParser(interpolation=None)
If you don't want to disable interpolation, you must escape the % sign by putting two consecutive %% in the properties file as shown in the example of the documentation.
Note that RawConfigParser is a legacy variant. From the python documentation:
Consider using ConfigParser instead which checks types of the values
to be stored internally. If you don’t want interpolation, you can use
ConfigParser(interpolation=None).
I know it's a really simple question, but I have no idea how to google it.
how can I do
print '%s' % (my_url)
So that my_url is used twice? I assume I have to "name" the %s and then use a dict in the params, but I'm not sure of the proper syntax?
just FYI, I'm aware I can just use my_url twice in the params, but that's not the point :)
print '%(url)s' % {'url': my_url}
In Python 2.6+ and Python 3, you might choose to use the newer string formatting method.
print('{0}'.format(my_url))
which saves you from repeating the argument, or
print('{url}'.format(url=my_url))
if you want named parameters.
print('{}'.format(my_url, my_url))
which is strictly positional, and only comes with the caveat that format() arguments follow Python rules where unnamed args must come first, followed by named arguments, followed by *args (a sequence like list or tuple) and then *kwargs (a dict keyed with strings if you know what's good for you).
The interpolation points are determined first by substituting the named values at their labels, and then positional from what's left.
So, you can also do this...
print('{}'.format(my_url, my_url, not_my_url=her_url))
But not this...
print('{}'.format(my_url, not_my_url=her_url, my_url))
Solution in Python 3.6+
Python 3.6 introduces literal string formatting, so that you can format the named parameters without any repeating any of your named parameters outside the string:
print(f'{my_url:s}')
This will evaluate my_url, so if it's not defined you will get a NameError. In fact, instead of my_url, you can write an arbitrary Python expression, as long as it evaluates to a string (because of the :s formatting code). If you want a string representation for the result of an expression that might not be a string, replace :s by !s, just like with regular, pre-literal string formatting.
For details on literal string formatting, see PEP 498, where it was first introduced.
You will be addicted to syntax.
Also C# 6.0, EcmaScript developers has also familier this syntax.
In [1]: print '{firstname} {lastname}'.format(firstname='Mehmet', lastname='Ağa')
Mehmet Ağa
In [2]: print '{firstname} {lastname}'.format(**dict(firstname='Mehmet', lastname='Ağa'))
Mehmet Ağa
For building HTML pages, you want to use a templating engine, not simple string interpolation.
Another option is to use format_map:
print('{s}'.format_map({'s': 'my_url'}))
As well as the dictionary way, it may be useful to know the following format:
print '%s' % (my_url, my_url)
Here it's a tad redundant, and the dictionary way is certainly less error prone when modifying the code, but it's still possible to use tuples for multiple insertions. The first %s is substituted for the first element in the tuple, the second %s is substituted for the second element in the tuple, and so on for each element in the tuple.
I recommend this syntax
dictionary_of_string_values = {
"my_text" : "go to w3schools",
"my_url" : "https://www.w3schools.com",
}
print ('{my_text}'.format(**dictionary_of_string_values))
It is very useful when you have to format a string with lots of placeholders.
You can also make it shorter like this:
print ('{my_text}'.format(
**{
"my_text" : "go to w3schools",
"my_url" : "https://www.w3schools.com",
}
)
)