How to convert ASCII characterers to Strings in Python - python

I am trying to compare an ASCII character that I am receiving from the serial port with a string. I am not able to do that, even though it seems like I have converted the inputs successfully.
Here is my code
import serial
import time
port="/dev/ttyUSB0"
serialArduino= serial.Serial(port,9600)
serialArduino.flushInput()
inputs=""
while True:
inputsp=serialArduion.readline()
for letter in inputsp:
inputs=inputs+ str(letter)
print inputs
if inputs=="DOWN":
print "APPLES"
elif inputs=="UP"
print "Bannana"
ok so even though the input sometimes equals UP OR DOWN it still does not print out APPLES or Bannana

The return value of readline() contains newline. You need to strip newline.
import serial
import time
port="/dev/ttyUSB0"
serialArduino= serial.Serial(port,9600)
serialArduino.flushInput()
while True:
inputs = serialArduion.readline().rstrip()
if inputs == "DOWN":
print "APPLES"
elif inputs == "UP"
print "Bannana"

try this:
while True:
inputsp=serialArduion.readline()
for letter in inputsp:
inputs=inputs+ chr(letter)
print inputs
if inputs.lower() =="down":
print "APPLES"
elif inputs.lower() =="up":
print "Bannana"
Just changed 'str' to 'chr', which converts ASCII to a character. Other than this modification, strip off any other characters coming from input stream.

Related

How to add incoming characters from UART to a string?

How do I add up incoming individual characters over UART to form a string?
For exmaple:
The characters from UART are printed in following format:
\x02
1
2
3
4
5
6
7
\X03
\x02
a
b
c
d
e
f
g
\x03
and I would like output to be something like:
1234567
abcdefg
I have tried this so far:
#!/usr/bin/env python
import time
import serial
ser = serial.Serial('/dev/ttyUSB0',38400)
txt = ""
ser.flushInput()
ser.flushOutput()
while 1:
bytesToRead = ser.inWaiting()
data_raw = ser.read(1)
while 1:
if data_raw !='\x02' or data_raw !='\x03':
txt += data_raw
elif data_raw == '\x03':
break
print txt
Any ideas on how to do that? I am getting no output using this.
First of all, you don't need to call inWaiting: read will block until data is available unless you explicitly set a read timeout. Secondly, if you do insist on using it, keep in mind that the function inWaiting has been replaced by the property in_waiting.
The string /x03 is a 4-character string containing all printable characters. The string \x03, on the other hand, contains only a single non printable character with ASCII code 3. Backslash is the escape character in Python strings. \x followed by two digits is an ASCII character code. Please use backslashes where they belong. This is the immediate reason you are not seeing output: the four character string can never appear in a one-character read.
That being out of the way, the most important thing to remember is to clear your buffer when you encounter a terminator character. Let's say you want to use the inefficient method of adding to your string in place. When you reach \x03, you should print txt and just reset it back to '' instead of breaking out of the loop. A better way might be to use bytearray, which is a mutable sequence. Keep in mind also that read returns bytes, not strings in Python 3.x. This means that you should be decoding the result if you want text: txt = txt.decode('ascii').
I would suggest a further improvement, and create an infinite generator function to split your steam into strings. You could use that generator to print the strings or do anything else you wanted with them:
def getstrings(port):
buf = bytearray()
while True:
b = port.read(1)
if b == b'\x02':
del buf[:]
elif b == b'\x03':
yield buf.decode('ascii')
else:
buf.append(b)
for item in getstring(Serial(...)):
print(item)
Here's one way that I think would help you a bit
l = []
while 1:
data_raw = ser.read(1)
if data_raw !='/x02' or data_raw !='/x03':
l.append(data_raw)
elif data_raw == '/x03':
txt = "-".join(l)
print txt
I begin by creating an empty list and each time you receive a new raw_data. you append it to the list. Once you reach your ending character, you create your string and print it.
I took the liberty of removing one of the loop here to give you a simpler approach. The code will not break by itself at the end (just add a break after the print if you want to). It will print out the result whenever you reach the ending character and then wait for a next data stream to start.
If you want to see an intermediate result, you can print out each data_raw and could add right after a print of the currently joined list.
Be sure to set a timeout value to None when you open your port. That way, you will simply wait to receive one bit, process it and then return to read one bit at a time.
ser = serial.Serial(port='/dev/ttyUSB0', baudrate=38400, timeout=None)
http://pyserial.readthedocs.io/en/latest/pyserial_api.html for mor information on that.

How do you print a variable as a string for the length of an input?

my task is when I type 'z' i get the outcome of 'w'.
This works.
However, if I input 'zzzz' only a single 'w' is outputted.
My question is how can I print 'w' for the number of times I enter z.
I am relatively new to StackOverflow. I'm sorry if I have broken any rules or my question is not correctly phrased.
z='w'
while True:
plaintext=input('enter a word to get its ciphertext')
i=list(plaintext)
print (i)
if 'z' in plaintext
print("w")
You are overcomplicating it. The variable you get from input() is a string. Simply use str.replace().
while True:
plaintext = input('enter a word to get its ciphertext')
plaintext_rep = plaintext.replace('z','w')
print(plaintext_rep)
Try looping through the text to get all of the letters
z='w'
while True:
plaintext=input('enter a word to get its ciphertext')
i=plaintext
for letter in i :
if(letter == 'z'):
print ('w')

Converting characters in a variable to their original ascii form

Okay, so I've been doing a lot of research and I couldn't find any answers so I came here to ask for some help.
My problem that I have encountered is I am having trouble taking a variable, then in the background of my code converting each individual string of that variable back to its ascii form and manipulating it using math, such as +, -, * and /. Here is my code..
Note: I had one theory, which is using a for loop to say for each character in this variable, do... blah blah. Here's my code anyways.
import random
import sys
import time
invalid_input = True
def start():
print("Welcome to the Encryption / Decryption Program!")
menuAnswer = input("Please select the number corresponding to the option you would like (1 - 3)\n---------------------------------\n[1] Encrypt\n[2] Decrypt\n[3] Exit the program\n---------------------------------\n")
if menuAnswer == '1':
print("You have chosen to Encrypt!")
invalid_input = False
message = open("sample.txt","r")
msgName = input("What is the name of the text document you would like to Encrypt?\n")
msgName = msgName.upper()
if msgName == 'SAMPLE':
key = '' #This variable will have the encryption key stored inside of it.
for i in range(0,8):
random_number = (random.randint(33,162)) #Generate a random ascii number from the range 33 to 162
key +=str(chr(random_number)) #Convert and store this ascii number as a character to the variable 'Key'
print(key)
print("Remember this key, as you will need it to decrypt your file!")
#\\ Offset //# #Finding the offset, must be able to convert each individual character of the key variable and return it to its usual form to manipulate using math.
else:
print("Invalid Filename")
elif menuAnswer == '2':
print("You have chosen to Decrypt!")
invalid_input = False
elif menuAnswer == '3':
print("You have chosen to exit!")
invalid_input = False
time.sleep(1)
print("Exiting...")
time.sleep(1.5)
exit()
else:
print("Invalid Input, Please try again!")
while invalid_input:
start()
Sorry if this question was difficult to understand, I am really confused myself and have been stuck on this for a week straight.
If I understand correctly you want to convert each character of your string to its ascii number and then do some sort of math operation on it and then convert it back to a string which you can do using ord() like so
s = 'Sample'
tmp = ''
for i in s:
tmp += chr(ord(i)+1)
print tmp
Tbnqmf
Although with the code you have you don't need to convert it to a string and then back to characters to manipulate it you can just manipulate it as soon as you pick a random number like so
import random
def start():
key = ''
for i in range(0,8):
random_number = (random.randint(33,162))
key +=chr(random_number+1)
print(key)
start()
Note you need to be careful when manipulating your characters since you could manipulate it to a number that is not an ascii character

Codeeval Challenge not returning correct output. (Python)

So I started doing the challenges in codeeval and i'm stuck at an easy challenge called "word to digit"
This is the challenge description:
Having a string representation of a set of numbers you need to print
this numbers.
All numbers are separated by semicolon. There are up to 20 numbers in one line. The numbers are "zero" to "nine"
input sample:
zero;two;five;seven;eight;four
three;seven;eight;nine;two
output sample:
025784
37892
I have tested my code and it works, but in codeeval the output is always missing the last number from each line of words in the input file.
This is my code:
import sys
def WordConverter(x):
test=str()
if (x=="zero"):
test="0"
elif (x=="one"):
test="1"
elif (x=="two"):
test="2"
elif (x=="three"):
test="3"
elif (x=="four"):
test="4"
elif (x=="five"):
test="5"
elif (x=="six"):
test="6"
elif (x=="seven"):
test="7"
elif (x=="eight"):
test="8"
elif (x=="nine"):
test="9"
return (test)
t=str()
string=str()
test_cases=open(sys.argv[1],'r')
for line in test_cases:
string=line.split(";")
for i in range(0,len(string)):
t+=WordConverter(string[i])
print (t)
t=str()
Am I doing something wrong? Or is it a Codeeval bug?
You just need to remove the newline char from the input. Replace:
string=line.split(";")
With
string=line.strip().split(";")
However, using string as the variable name is not a good decision...
When iterating over the lines of a file with for line in test_cases:, each value of line will include the newline at the end of the line (if any). This results in the last element of string having a newline at the end, and so this value won't compare equal to anything in WordConverter, causing an empty string to be returned. You need to remove the newline from the string at some point.

Restricting the User Input to Alphabets

I'm a technical writer learning python. I wanted to write a program for validating the Name field input,as a practise, restricting the the user entries to alphabets.I saw a similar code for validating number (Age)field here, and adopted it for alphabets as below:
import string
import re
r = re.compile(r'[a-zA-Z]+')
print "WELCOME FOR NAME VERIFICATION. TYPE ALPHABETS ONLY!"
print raw_input("Your Name:")
x = r
if x == r:
print x
elif x != r:
print "Come on,'", x,"' can't be your name"
print raw_input("Your Name:")
if 5<=len(x)<=10:
print "Hi,", x, "!"
elif len(x)>10:
print "Mmm,Your name is too long!"
elif len(x)<5:
print "Alas, your name is too short!"
raw_input("Press 'Enter' to exit!")
I intend this code block to do two things. Namely, display the input prompt until the user inputs alphabets only as 'Name'. Then, if that happens, process the length of that input and display messages as coded. But, I get two problems that I could not solve even after a lot of attempts. Either, even the correct entries are rejected by exception code or wrong entries are also accepted and their length is processed.
Please help me to debug my code. And, is it possible to do it without using the reg exp?
If you're using Python, you don't need regular expressions for this--there are included libraries which include functions which might help you. From this page on String methods, you can call isalpha():
Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.
I would suggest using isalpha() in your if-statement instead of x==r.
I don't understand what you're trying to do with
x = r
if x == r:
etc
That condition will obviously always be true.
With your current code you were never saving the input, just printing it straight out.
You also had no loop, it would only ask for the name twice, even if it was wrong both times it would continue.
I think what you tried to do is this:
import string
import re
r = re.compile(r'[a-zA-Z]+')
print "WELCOME FOR NAME VERIFICATION. TYPE ALPHABETS ONLY!"
x = raw_input("Your Name:")
while not r.match(x):
print "Come on,'", x,"' can't be your name"
x = raw_input("Your Name:")
if 5<=len(x)<=10:
print "Hi,", x, "!"
elif len(x)>10:
print "Mmm,Your name is too long!"
elif len(x)<5:
print "Alas, your name is too short!"
raw_input("Press 'Enter' to exit!")
Also, I would not use regex for this, try
while not x.isalpha():
One way to do this would be to do the following:
namefield = raw_input("Your Name: ")
if not namefield.isalpha():
print "Please use only alpha charactors"
elif not 4<=len(namefield)<=10:
print "Name must be more than 4 characters and less than 10"
else:
print "hello" + namefield
isalpha will check to see if the whole string is only alpha characters. If it is, it will return True.

Categories