Erlang - Converting String to Binary - string

Consider this variable
X = "1_2_3_4",
How to I get X into a binary string format?
So like this
<<"1_2_3_4">>
I'm getting all manner of errors trying to figure it out.
Thanks in advance,
Snelly.

Use the built in conversion function.
list_to_binary(X).

Thanks Dave! I had a quite a complex function concatinating variables
and strings/integers/atoms etc.
In case you are interested:
convert(L) ->
convert(L, <<>>).
convert([], Bin) ->
Bin;
convert([H|T], Bin) ->
convert(T, <<Bin/binary, H>>).
(what I was thinking of as Strings) as lists! Confusing
I think the reason that it's confusing is because sometimes the shell prints out a list as a string and sometimes it doesn't. In my opinion, things would be much clearer if the shell always output a list as a list unless you specifically requested a string.

Related

Twincat3 ST variables conversion

I have some complicated array of structures and I want to write it into CSV file. So I need "variable to string" conversion.
Beckhoff as always doesn't care about documentation and their INT_TO_STRING function doesn't work (UNEXPECTED INT_TO_STRING TOKEN when I try to write INT_TO_STRING(20) ).
Moreover their string functions works correctly with only 255 chars.
So I need one of following:
working functions or function blocks or library which allows to convert different types to string
something like sprintf without limitations
some functions to convert between number and ascii char (0x55 is letter 'U') in both directions.
btw. Beckhoff gives us some weird CSV example code, but without data conversion (array has already strings in cells).
Thanks in advance!
I tried to use:
INT_TO_STRING() BYTE_TO_STRING() WHATEVER_TO_STRING()
but it is not working. And there is no clue how many arguments it should have or anything. There is no documentation in Beckhoff information System.

How do I change the type of a string to a bytestring?

For example, I have '\x87' and I want b'\x87'.
I know, that there exists .encode(), but when I execute ('\x87').encode(), I get b'\xc2\x87' and not b'\x87'.Is there any way to tell python that it should interpret the given string as a bytestring without possibly changing it in any way?
Try this.
my_str = '\x87'
my_str_as_bytes = my_str.encode(encoding='latin')
One possible solution is:
bytes(ord(x) for x in '\x87')

String formatting in python 3 without print function

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.

Turning a list into a set of coordinates [Haskell]

I am a starting out programmer and have my first few programming classes. We started off with functional programming, in this case using Haskell. I've managed to complete a few assignments already, but seem to have gotten stuck in one point and was hoping to get some help with it.
In order to not bore you with the entire code, my program right now is extracting a list of commands from a text file. I need to turn this list into a set of coordinates. What I mean is something along the lines of:
function :: [String] -> (Int, Int, Char)
where the function will receive, for example, the list ["0 0 N"] and output the coordinates and direction (0, 0, N).
I tried doing:
function [x y o] = (show x, show y, read o)
which would work if it were just Integers. I can't seem to get the Char part to work. I appologize if it's such a noobie question, but bear with me, please, I'm really new to all of this.
Thank you and best regards!
For your specific test case this should work:
function [(x:' ':y:' ':o:_)] = (read [x], read [y], o)
If your string contains spaces you need to match on them as well if you want to do it like that.
But that's probably not what you actually want. It would break for inputs like ["12 23 S"] or ["3 5 W", "2 8 E"].
If your input is actually a list of Strings like your signature says you should probably write two functions: One that deals with a single String and one that applies your other function to all Strings in the list. Look at the functions map and words and think about how you can use them to solve your problem.

Replacing or substituting in a python string does not work

I could almost solve all of my python problems thanks to this great site, however, now I'm on a point where I need some more and specific help.
I have a string fetched from a database which looks like this:
u'\t\t\tcase <<<compute_type>>>:\n\t\t\t\t{\n\t\t\t\t\tif (curr_i <= 1) Messag...
the string is basically plain c code with unix line endings and supposed to be treated in a way that the values of some specific variables are replaced by something else gathered from a Qt UI.
I tried the following to do the replacing:
tmplt.replace(u"<<<compute_type>>>", str(led_coeffs.compute_type))
where 'led_coeffs' is a namedtuple and its value is an integer. I also tried this:
tmplt = Template(u'\t\t\tcase ${compute_type}:\n\t\t\t\t{\n\t\t\t\t\tif (curr_i <= 1) Messag...)
tmplt.substitute(compute_type = str(led_coeffs.compute_type))
however, both approaches do not work and I have no idea why. Finally I was hoping to get some input here. Maybe the whole approach is not right and any hint on how to achieve the replacing in a good manner is highly appreciated.
Thanks,
Ben
str.replace (and other string methods) don't work in-place (string in Python are immutable) - it returns a new string - you will need to assign the result back to the original name for the changes to take effect:
tmplt = tmplt.replace(u"<<<compute_type>>>", str(led_coeffs.compute_type))
You could also invent your own kind of templating:
import re
print re.sub('<<<(.*?)>>>', lambda L, nt=led_coeffs: str(getattr(nt, L.group(1))), your_string)
to automatically lookup attributes on your namedtuple...

Resources