Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Python How can i use this to translate entire words at a time?

SilentHealer584

New Coder
I got some code here(can anyone help solve this problem?):

JavaScript:
while True:
    n = raw_input("Ltr:")
    if n.strip() == 'a':
        print("01100001")
        repeat='while True'

    if n.strip() == 'b':
        print("01100010")
        repeat='while True'
#it goes on for every letter of the english alphabet

Basically it is a Letter to Binary translator (i made it my self and im very happy of how it turned out:))
, the only problem is it can only translate one letter at a time, does anyone have any idea of how I can make it translate entire words, or even sentences ?
 
Hello! I am so glad I saw this.
There is a much easier way to convert to binary! You do not need your if statements!

[CODE lang="python" title="text to binary in Python"]while True:
n = input("Ltr:") # use raw_input in python 2x or input() preferred
if len(n) > 0:
binarystring = ' '.join(format(ord(letter), '08b') for letter in n)
print("BINARY:\n"+str(binarystring))
[/CODE]

As you can see here, we use the input (you should update your Python version to 3x+ by the way), and then we say if the length of our string is over 0, convert it.
The join() will construct a string (binarystring) by adding the result whatever is inside the join (our format() ) to whatever precedes it - in this case I use ' ', to make sure a blank space is between each letter's binary. When we use format() with ord() we are getting an integer/unicode value for the letter. Then the format's 2nd parameter "08b" is turning to binary because "0" means take position 0 (the current letter we're on), "8" means format it into a value that is 8 characters long (for binary) with 0s added to the left as needed, and finally the "b" means we get the binary version. We do this for each letter in our input and then print the resulting binary answer!
 

New Threads

Buy us a coffee!

Back
Top Bottom