String formatting in python 3 without print function - python-3.x

Trying to understand how "%s%s" %(a,a) is working in below code I have only seen it inside print function thus far.Could anyone please explain how it is working inside int()?
a=input()
b=int("%s%s" %(a,a))

this "%s" format has been borrowed from C printf format, but is much more interesting because it doesn't belong to print statement. Note that it involves just one argument passed to print (or to any function BTW):
print("%s%s" % (a,a))
and not (like C) a variable number of arguments passed to some functions that accept & understand them:
printf("%s%s,a,a);
It's a standalone way of creating a string from a string template & its arguments (which for instance solves the tedious issue of: "I want a logger with formatting capabilities" which can be achieved with great effort in C or C++, using variable arguments + vsprintf or C++11 variadic recursive templates).
Note that this format style is now considered legacy. Now you'd better use format, where the placeholders are wrapped in {}.
One of the direct advantages here is that since the argument is repeated you just have to do:
int("{0}{0}".format(a))
(it references twice the sole argument in position 0)
Both legacy and format syntaxes are detailed with examples on https://pyformat.info/
or since python 3.6 you can use fstrings:
>>> a = 12
>>> int(f"{a}{a}")
1212

% is in a way just syntactic sugar for a function that accepts a string and a *args (a format and the parameters for formatting) and returns a string which is the format string with the embedded parameters. So, you can use it any place that a string is acceptable.
BTW, % is a bit obsolete, and "{}{}".format(a,a) is the more 'modern' approach here, and is more obviously a string method that returns another string.

Related

Extracting variables from expression in Lua

I have expressions in lua which contains standard metatable operations .__add,.__sub,.__mul, (+,-,*)
For example a+b*xyz-cdeI am trying to extract all free variables in table. For this expression, the table will contain {a,b,xyz,cde}. Right now I am trying it with string operations, like splitting, substituting etc. This seems to work but I feel it as ugly way. It gets little complicated as there may nesting and brackets involved in expressions. For example, the expression (a+b)-c*xyz*(a+(b+c)) should return table {a,b,c,xyz}. Can there be a simple way to extract free variables in expressions? I am even looking for simple way with string library.
If you want to do string processing, it's easy:
local V={}
local s="((a+b)-c*xyz*(a+(b+c)))"
for k in s:gmatch("%a+") do
V[k]=k
end
for k in pairs(V) do print(k) end
For fun, you can let Lua do the hard work:
local V={}
do
local _ENV=setmetatable({},{__index=function (t,k) V[k]=k return 0 end})
local _=((a+b)-c*xyz*(a+(b+c)))
end
for k in pairs(V) do print(k) end
This code evaluates the expression in an empty environment where every variable has the value zero, saving the names of the variables in the expression in a table.

How to change a string into a variable

I want to write out some data into a file. I saved the filename as a variable. I wan to use % mode to substitude the variable to the text, but it gives an error:
IndentationError: unindent does not match any outer indentation level
writeafile = open('N:\myfile\%s.txt' , "a") % (variable)
Assuming we are talking about Python here, you should move variable next to the
'N:\\myfile\\%s.txt' string for correct syntax, like so:
writeafile = open("N:\\myfile\\%s.txt" % variable, "a")
However, using this style of formatting is not recommended by Pydocs:
The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer formatted string literals, the str.format() interface, or template strings may help avoid these errors. Each of these alternatives provides their own trade-offs and benefits of simplicity, flexibility, and/or extensibility.
Source
So, I'd suggest using f-strings, which have been available in Python since 3.6. The double \\ is intentional here, otherwise Python will treat it as an escape character and you'll get undesired results.
writeafile = open(f"N:\\myfile\\{variable}.txt", "a")
Alternatively, you could also use str.format():
writeafile = open("N:\\myfile\\{name}.txt".format(name=variable), "a")

What is %s+ or %s used for in lua and how do you use it?

How do i use %s in lua, or a better question would be how is it used?
so here is what i have tried before assuming this is how it is used and how it works.
local arg1 = 'lmao'
print('fav string is %arg1')
at first i thought it was something used to reference a string or numeral inside of a string without doing like
print('hello '..name..'!')
Can someone provide me some examples or a explanation on how this is used and what for?
A % in a string has no meaning in Lua syntax, but does mean something to certain functions in the string library.
In string.format, % is used to make a format specifier that converts another argument to a string. It's documented at string.format, but that refers to Output Conversion Syntax and Table of Output Conversions to explain almost all of the specifier syntax.
The % is also used to designate a character class in the pattern syntax used with some string functions.
Here is your code using string.format:
local arg1 = 'lmao'
print(string.format('fav string is %s', arg1))
Or, taking advantage of the string metatable:
local arg1 = 'lmao'
print(('fav string is %s'):format(arg1))
Lua uses %s in patterns (Lua's version of regular expressions) to mean "whitespace". %s+ means "one or more whitespace characters".
Ref: https://www.lua.org/manual/5.3/manual.html#6.4.1

Assigning a mathematical string expression to double variable

I have a mathematical expression in string form like:
string strExpression = "10+100+Math.Sin(90)";
I want to simply assign this expression (at run time) to a float variable (say result), so that it becomes the following code statement:
float result = 10+100+Math.Sin(90);
How can I do this?
You have to compile the expression within a syntactically correct code block. See http://devreminder.wordpress.com/net/net-framework-fundamentals/c-dynamic-math-expression-evaluation/ as an example.
Edit: Or alternatively write your own expression parser if the expression is going to be VERY simple (I wouldn't recommend this though)
You could use CS-Script to dynamically make a class with a method that you can run, if you don't want to write your own parser but rather use C# which you allready know..

Lua string.format options

This may seem like a stupid question, but what are the symbols used for string replacement in string.format? can someone point me to a simple example of how to use it?
string.format in Lua follows the same patterns as Printf in c:
https://cplusplus.com/reference/cstdio/printf/
There are some exceptions, for those see here:
http://pgl.yoyo.org/luai/i/string.format
Chapter 20 of PiL describes string.format near the end:
The function string.format is a
powerful tool when formatting strings,
typically for output. It returns a
formatted version of its variable
number of arguments following the
description given by its first
argument, the so-called format string.
The format string has rules similar to
those of the printf function of
standard C: It is composed of regular
text and directives, which control
where and how each argument must be
placed in the formatted string.
The Lua Reference says:
The format string follows the same
rules as the printf family of standard
C functions. The only differences are
that the options/modifiers *, l, L, n,
p, and h are not supported and that
there is an extra option, q.
The function is implemented by str_format() in strlib.c which itself interprets the format string, but defers to the C library's implementation of sprintf() to actually format each field after determining what type of value is expected (string or number, essentially) to correspond to each field.
There should be "Lua Quick Reference" html file in your hard disk, if you used an installation package.
(for example: ../Lua/5.1/docs/luarefv51.html)
There you'll find, among other things,
string.format (s [, args ])
Formatting directives
Formatting field types
Formatting flags
Formatting examples
To add to the other answers: Lua does have a boolean data type, where C does not. C uses numbers for that, where 0 is false and everything else is true.
However, to format a boolean in a String in Lua,
local text = string.format("bool is %d", truth)
gets (at least in Hammerspoon):
bad argument #2 to 'format' (number expected, got boolean)
You can instead use %s for booleans (as for strings):
local text = string.format("bool is %s", truth)

Resources