Python string formatting when already "{}" in the string - 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}'

Related

Is it possible to use format() function with a string in format's place?

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'

can we use input() in subprocess to assign value in parameter

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))

String formatting with *args

I looked at the following few posts and wasn't quite able to figure out what I want to do.
python - How to format variable number of arguments into a string?
Pass *args to string.format in Python?
What I want to do is simple. Given some array of variable length I want to be able to print all the arguments individually. That is, I want
print('{} {} ...'.format(*arg))
Obviously I won't be able to predict how many {} I will need before hand and I tried len(x)*'{}' which didn't yield what I wanted. If I leave that out then I only get the first argument. What is the way to achieve this?
so why not just:
print(" ".join(map(str,args)))
which does the same thing as {} {} ... in format
Why use a format string at all? print can do this for you:
print(*arg)

Python Substituiting a float only giving whole number

I'm reading into a csv file an extracting a piece of data with the line:
x = float(node[1])
when I print(x), I get the correct value or the exact value found in the cell. e.g 153.018848
But when I try to pass x as variable in the following:
print('<node version="0" lon="%d">' %(x))
the output will be <node version="0" lon="153"> . Of course I want the value 153.018848.
What have I overlooked?
Thanks in advance.
You've overlooked the fact that %d is for integers. Try %f instead.
You're using the wrong format flag. %d is for integers, use %f for floats.
You want to replace your %d with %f, problem solved ;)
See: http://docs.python.org/release/2.5.2/lib/typesseq-strings.html
For bonus points, are you aware you can put together long format strings that are still readable using dictionaries? You can read more about it, but the !r option I have used with call the repr() function on the variable, so you know what is inserted will be exactly what you've seen printed in your debugging:
string = """<tagname id=%{idval!r} type=%{tagtype!r} foo=%{bar!r}"""
print string.format( **{'idval':var1, 'tagtype':var2, 'bar':var3})

String formatting named parameters?

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",
}
)
)

Categories

Resources