This question already has answers here:
How do I put a variable’s value inside a string (interpolate it into the string)?
(9 answers)
Closed 2 years ago.
I have a function call as follow:
send_at('AT+CMQPUB=0,"sensor",1,0,0,34',"hex_numbers_here",'OK',10)
I want the "34" and the "hex_numbers_here" to be variables instead of literal inputs, but my attempts to "escape" out of the quotes are failing miserably...
Please help!
I tried:
send_at('AT+CMQPUB=0,"sensor",1,0,0,'+myval+',"'+my_hex+'",'OK',10)
where myval and my_hex are the variables I created earlier in my code.
update:
I tried the following as well now:
mqtt_msg = b'testing mqtt message from sim7020'
output = binascii.b2a_hex(mqtt_msg)
length = len(output)
print(output)
output_text = str(output)
print(output_text)
f1 = 'AT+CMQPUB=0,"sensor",1,0,0,'+str(length)+',"'+output_text+'"'
f2 = 'OK'
f3 = '10'
print(f1)
AT+CMQPUB=0,"sensor",1,0,0,66,"b'74657374696e67206d717474206d6573736167652066726f6d2073696d37303230'"
The only thing noiw is that the output_text variable should not contain the b'' - making me think that the casting to str() of the hex/bit value is now doing what I think it should be doing...
BTW - I HAVE to cast the text to binary/hex - this is what the modem wants...
UPDATE:
OK, I found a way around this that is working now:
mqtt_msg = b'testing mqtt message from sim7020 - and again!'
output = binascii.b2a_hex(mqtt_msg)
length = len(output)
print(output)
output_text = str(output)
print(output_text)
output_text = output_text[2:length+2]
new_len = len(output_text)
f1 = 'AT+CMQPUB=0,"sensor",1,0,0,'+str(new_len)+',"'+output_text+'"'
f2 = 'OK'
f3 = '10'
print(f1)
I'm basically just stripping out the first 2 and last chars from the string.
What about this?
def send_at(p1, p2, p3, p4):
print(p1, p2, p3, p4)
send_at('AT+CMQPUB=0,"sensor",1,0,0,{}'.format(34), '{}'.format('FC0012'), 'ok', 10)
Output:
AT+CMQPUB=0,"sensor",1,0,0,34 FC0012 ok 10
Related
This question already has answers here:
Changing variable name in loop
(2 answers)
How to turn a string into a variable name within a loop?
(1 answer)
Closed 8 months ago.
In Matlab, I want to create a series of variables based on an array of strings.
As a simplified example, from the given matrixes A1, A2, B1, and B2, I want to create variables A and B as their corresponding combined matrixes. Kindly teach me how to do that. It is very much appreciated.
I have tried the below code, which does not work.
% Simplified examples of given matrixes
A1 = [1;2];
A2 = [3;4];
B1 = [5;6];
B2 = [7;8];
% What I need
ATest = cat(1, A1, A2);
BTest = cat(1, B1, B2);
% I have many of A, B, …, thus looking for a loop of string array, but below trying does not work.
VarList = {'A', 'B'};
for ivar = 1:length(VarList)
eval(['%d = cat(1, %d1, %d2);', VarList(ivar)));
end
Added: (a temporary solution for my desire). Note the use of VarList{ivar} instead of VarList(ivar). I should note it as temporary since caution (for the problem of dynamic variables) may be needed.
VarList = {'A', 'B'};
for ivar = 1:length(VarList)
v = VarList{ivar};
eval([v '=cat(1,' v '1,' v '2);']);
end
This question already has answers here:
python .lower() is not working [duplicate]
(3 answers)
Closed 1 year ago.
I don't know what I'm doing wrong here. Please help.
def AddColon (data):
data.strip() # --> to remove the spaces
result = ''
for i in range (len(data)):
if str(data[i]).isalpha(): # to only include letters
result = result + data[i]
result.lower() # to make everything lowercase
result[0].upper() # to make the first letter uppercase
finalresult = result + ' : Hello'
return finalresult
input1 = input('Insert Data : ')
print(AddColon(str(input1)))
If your input contains any numbers or integers it may not go under if condition and the result will not be updated. To get a exact value, u may need to give only strings as input not alphanumeric.After that remove the indentation in for loop and if condition...try removing that and run your code. Your code and output is ready.
I am trying to iterate over some integer values and insert them into an string which has to be in a weird format to work. The exact output (including the outer quotes) I need if the value was 64015 would be:
"param={\"zip\":\"64015\"}"
I have tried f string formatting but couldn't get it to work. It has problem with the backslashes and when I escaped them the output was not exactly like above string
Hopefully, I made myself clear enough.
You would have to escape the backslash and the double quotes seperately like this:
string = '"param={\\\"zip\\\":\\\"' + str(64015) + '\\\"}"'
The result of this is:
"param={\"zip\":\"64015\"}"
You can use alternate ways to delimit the outer string ('...', '''...''', """...""") or use str.format() or old style %-formatting syntax to get there (see f-style workaround at the end):
s = s = 'param={"zip":"' + str(64015) + '"}'
print(s)
s = '''param={"zip":"''' + str(64015) +'''"}'''
print(s)
s = """param={"zip":"64015"}""" # not suited for variable replacement
print(s)
s = 'param={{"zip":"{0}"}}'.format(64015)
print(s)
s = 'param={"zip":"%s"}' % 64015
print(s)
Output:
param={"zip":"64015"}
param={"zip":"64015"}
param={"zip":"64015"}
param={"zip":"64015"}
If you need any "\" in there simply drop a \\ in:
s = '"param={\\"zip\\":\\"' + str(64015) + '\\"}"'
print(s)
s = '''"param={\\"zip\\":\\"''' + str(64015) +'''\\"}"'''
print(s)
s = '"param={{\\"zip\\":\\"{0}\\"}}"'.format(64015)
print(s)
s = '"param={\\"zip\\":\\"%s\\"}"' % 64015
print(s)
Output:
"param={\"zip\":\"64015\"}"
"param={\"zip\":\"64015\"}"
"param={\"zip\":\"64015\"}"
"param={\"zip\":\"64015\"}"
The f-string workaround variant would look like so:
a = '\\"'
num = 64015
s = f'"param={{{a}zip{a}:{a}{num}{a}}}"'
and if printed also yields :
"param={\"zip\":\"64015\"}"
More on the topic can be found here: 'Custom string formatting' on python.org
I played around a bit with f-strings and .format() but ultimately got this to work:
foo = 90210
bar = '"param={\\"zip\\":\\"%s\\"}"' % (foo)
print(bar)
giving:
"param={\"zip\":\"90210\"}"
Hopefully someone can give you an f-string alternative. I kept running into unallowed "\" in my f-string attempts.
Is it only this?
a = "param={\"zip\":\"64015\"}"
b = a.split('=')
c = eval(b[1])
print(c)
print(c['zip'])
Result:
{'zip': '64015'}
64015
Please note that evaluating (eval()) strings from unknown source may
be dangerous! It may run the code that you are not expecting.
First question here.
I am picking up Python and have a question that may be quite basic.
I am trying to create this pattern with a nested loop:
x
x
x
xxx
With the code:
numbers = [1,1,1,3]
for count_x in numbers:
output = ""
for count in range(count_x):
output +=x
print(output)
My question is - why does my output change when I move the position of print(output).
The code above works but when I align print(output) with the for count_x in numbers:, I only get "xxx", when I align print(output) to output +=x, I get the following:
x
x
x
x
xx
xxx
which is very odd because there are only 4 items in the list and it shows me 6 lines of output.
Could someone please help? Really puzzled. Thank yall very much.
There's a difference between these two bits of code (fixing the x/"x" problem along the way - your code won't actually work as is unless you have a variable x):
# First:
numbers = [1,1,1,3]
for count_x in numbers:
output = ""
for count in range(count_x):
output += "x"
print(output)
# Second:
numbers = [1,1,1,3]
for count_x in numbers:
output = ""
for count in range(count_x):
output += "x"
print(output)
In the second, the print is done inside the loop that creates the string, meaning you print it out multiple times while building it. That's where your final three lines come from: *, ** and ***. This doesn't matter for all the previous lines since there's no functional difference. Printing a one character string at the end or after adding each of the one characters has the same effect.
In the first, you only print the string after fully constructing it.
You can see this effect by using a slightly modified version that outputs different things for each outer loop:
numbers = [1,1,1,3]
x = 1
for count_x in numbers:
output = ""
for count in range(count_x):
output += str(x)
print(output)
x += 1
This shows that the final three lines are part of a single string construction (comments added):
1 \
2 >- | Each is one outer/inner loop.
3 /
4 \ | A single outer loop, printing
44 >- | string under construction for
444 / | each inner loop.
In any case, there are better ways to do what you want, such as:
numbers = [1,1,1,3]
for count_x in numbers:
print('x' * count_x)
You could probably also do it on one line with a list comprehension but that's probably overkill.
This question already has answers here:
How do I clone a list so that it doesn't change unexpectedly after assignment?
(24 answers)
Closed 5 years ago.
I don't understand why my code doesn't work.
The code is:
def trans(old):
length = len(old)
new = []
new = old
for i in range(0,length):
print(old[length-i-1])
for i in range(0,length):
new[i] = old[length-i-1]
print("new:",new[i]," [i]:",i," old:",old[length-i-1]," length-
i-1:",length-i-1)
ihavenoideawhatimdoing = " ".join(new)
return new
Instruction:
1. def trans(old): Input sentence in (old)
2. length(len): Take number of elements in the sentence
3. new = [] and new = old is to make a container with the same size for the new word
4. First for loop = I wanted to see the words in the original sentence backwards
5. My problem is in the second for loop. See the output
6. What comes next is related to the problem I'm solving but not to the problem I'm having
Output
Input sentence: "please help me solve this"
I didn't any label for the next batch of words but it's supposed to be:
old(length-0-1) -> old(5-0-1) -> old(4): this
old(3): solve
old(2): me
old(1):help
old(0): please
Now, what's iffy is in the next for statement at length-i-1 = 1 where instead of being "help", it's "solve."
Both codes are familiar so I'm stuck at what else could be wrong.
Use this:
def trans(old):
new = old.split(" ")
new_str = ""
for i in reversed(new):
new_str = new_str + " " + i
print new_str