Python format() combined with join and data conversion - python-3.x

This Python code gives exactly what I want:
a_hex_str = ':'.join('%02x' % b for b in a_bytes)
which is a string of the byte values in the byte array a_bytes printed in hex with a colon between each value.
I have been going mad trying to get the same output using the new format() function in place of the old % but all my attempts give errors.
I would be very grateful for assistance.

a_hex_str = ':'.join('{}02x'.format(b) for b in a_bytes)
Try this line hopefully it will work.

a_hex_str = ':'.join('{:02x}'.format(b) for b in a_bytes)
I adapted the answer from
https://stackoverflow.com/questions/5661725/format-ints-into-string-of-hex
I didn't realise I needed the colon inside the curly braces, otherwise it gives an out of range error.

Related

Lua unicode, using string.sub() with two-byted chars

As example: I want remove the first 2 letters from the string "ПРИВЕТ" and "HELLO." one of these are containing only two-byted unicode symbols.
Trying to use string.sub("ПРИВЕТ") and string.sub("HELLO.")
Got "РИВЕТ" and "LLO.".
string.sub() removed 2 BYTES(not chars) from these strings. So i want to know how to get the removing of the chars
Something, like utf8.sub()
The key standard function for this task is utf8.offset(s,n), which gives the position in bytes of the start of the n-th character of s.
So try this:
print(string.sub(s,utf8.offset(s,3),-1))
You can define utf8.sub as follows:
function utf8.sub(s,i,j)
i=utf8.offset(s,i)
j=utf8.offset(s,j+1)-1
return string.sub(s,i,j)
end
(This code only works for positive j. See http://lua-users.org/lists/lua-l/2014-04/msg00590.html for the general case.)
There is https://github.com/Stepets/utf8.lua, a pure lua library, which expand standard function to support utf8 string.
I found a simpler solution (the the solution using offset() didnt work for me for all cases):
function utf8.sub(s, i, j)
return utf8.char(utf8.codepoint(s, i, j))
end

Python how to remove the first set of a character in a string?

My variable x has a value of "000032403" and I want to remove the first set of zeros but I want to keep the other! How I gonna do that?
Note: Please give me any suggestions without knowing the amount of zeros in the beginning, because in my program this value is obtained from the user.
You can use the lstrip() function of the string class like this
>>> x = "000032403"
>>> x.lstrip("0")
"32403"
This will "return a copy of the string with leading characters removed".
Here's a link to the docs

Adding Hyphen within a spliced string

Continuing from my last question (which, btw, thanks for the help!), I'm stuck on how to add a hyphen to separate my string. Here's what I have so far:
original = "1234567890"
def fixPhoneNum(original):
original = list(original)
original[0], original[9] = original[9], original[0]
original[1:5], original[5:8] = original[5:8], original[1:5]
original = ''.join(original)
original = print(original[0:3], end="-"), print(original[3:7], end="-"), print(original[5:9])
return
Edit The above code doesn't give me the result I'm looking for
So basically, I took the original string of numbers, switched the first and last and the intermediary values with each other. Now I want to separate the first 3 digits, the next 3 digits with a hyphen.
Any help? This is driving me crazy.
Thanks!
I do not quite understand the rule for character ordering in your question.
Here is a simpler example of str.format function which accepts "0123" and produces "30-21" permutation with a hyphen. Hope it answers the question.
instr = "0123"
outstr = '{0[3]}{0[0]}-{0[2]}{0[1]}'.format(instr)
If you are not familiar with format strings, start with examples in the docs: https://docs.python.org/3/library/string.html#formatexamples

Python: numerical elements in a list cant be converted into integers

Hello people,
I've got a problem with my code. For some reason the values are not converted to integers from strings and are not adding up. Here is my code.
def SumOfState(i,j):
cf=readPopest(file1)
sum2=[]
sum7=[]
Diff=0
for y in range((j)):
StateList=str(cf[y+i]).split(',')
sum2.append(StateList[2])
sum7.append(StateList[7])
results2 = [int(i) for i in sum2]
results7 = [int(i) for i in sum7]
print sum(results2)
print sum(results7)
Error message : Inappropriate argument value (of correct type).
An error occurred attempting to pass an argument to a function.
cf=readPopest(file1)
the code ^^ gives a list containing words and numbers. One element is taken % split into sublists.
Ive tried the int() function and the for loop variant of it.
suggest me an edit, please.
Really appreciate any help.
Thanks.
-Addie Vanhala
I guess looking at you code, it is because sum2 and sum7 contain non integers, probably because some part of file1 (accessed though readPopest) is non int.

How do I concatenate a string stored in variable and a number in MATLAB

I am trying to read a tag from XML and then want to concatenate a number to it.
Firstly, I am saving the value of the string to a variable and trying to concatenate it
with the variable in the for loop. But it throws an error.
for i = 0:tag.getLength-1
node = tag.item(i);
disp([node.getTextContent]);
str=node.getTextContent;
str= strcat(str, num2str(i))
new_loads = cat(2,loads,[node.getTextContent]);
end
Error thrown is
Operands to the || and && operators must be
convertible to logical scalar values.
Error in strcat (line 83)
if ~isempty(str) && (str(end) == 0 ||
isspace(str(end)))
Error in SMERCGUI>pushbutton1_Callback (line 182)
str= strcat(str,' morning')
Error in gui_mainfcn (line 96)
feval(varargin{:});
Error in SMERCGUI (line 44)
gui_mainfcn(gui_State, varargin{:});
Error in
#(hObject,eventdata)SMERCGUI('pushbutton1_Callback',hObject,eventdata,guidata(hObject))
Error while evaluating uicontrol Callback
The error suggests that your string is not a string. It's not clear to me whether it's throwing an error at the strcat line, or at the later cat line.
At any rate, it should be clear that you cannot concatenate elements of different types into an array - cell array yes, regular array no. So the line
new_loads = cat(2,loads,[node.getTextContent]);
is bound to give a problem. 2 is numerical, and node.getTextContent is a string - or maybe a cell array or something else. I can't see what loads is, so I can't tell if that is involved in the problem.
Usually a good way to combine numbers and strings into a single string is
newString = sprintf('%s %d', oldString, number);
You can then use all the formatting tricks of printf to produce output exactly as you want. But before you do anything, make sure you understand the type of all the elements you are trying to string together. The easiest way to do this for all the elements in memory is
whos
Or if you just want it for one variable,
whos str
Or all variables starting with s:
whos s*
The output is self-explanatory. If you still can't figure it out after this, leave a comment and I'll try to help you out.
EDIT based on what I read at http://blogs.mathworks.com/community/2010/11/01/xml-and-matlab-navigating-a-tree/ , it is possible that you just need to cast your str variable to a Matlab string (apparently it's a java.lang.string). So try to add
str = char(str);
before using str. It may be what you need.

Resources