0

I'm new to Python. Trying to make a simple function that converts a string input to braille via dict values (with '1' indicating a bump and 0 no bump).

I'm sure there are faster/better ways to do this but what I have is almost working (another way of saying it doesn't work at all).

alphabet = {
'a': '100000','b': '110000','c': '100100','d': '100110'
#etc
}
def answer(plaintext):

    for i in str(plaintext):
        for key, value in alphabet.iteritems():
            if i in key:
                print value,            

answer('Kiwi')

This prints:

000001101000 010100 010111 010100

My question is how do I remove the spaces? I need it to print as:

000001101000010100010111010100

It's printing as a tuple so I can't use .strip().

2

5 Answers 5

1

For what I'd consider a pythonic way:

def answer(plaintext):
    alphabet = { ... }
    return "".join([alphabet[c] for c in plaintext])

(this assumes that all letters in plaintext are in alphabet)

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks so much! This works perfectly. I understand the looping through each c in plaintext, and that the dict values are being joined without spaces, but can you briefly explain how the rest works - specifically the alphabet[c] ?
alphabet is a dict, so alphabet[c] is the encoding for that letter in the plaintext
I understand. Thanks again.
0
brail = []
for i in str(...):
  if alphabet.get(i):
    brail.append(alphabet[i])
print ''.join(brail)

Comments

0

In the first line of the function, create a container l=[] .Change the last statement inside the loops to l.append(value).Outside the loops,but still inside the function, do return ''.join(l). Should work now.

Comments

0

You can use join() within a generator like this way:

alphabet = {'a': '100000','b': '110000','c': '100100','d': '100110'}

def answer(a = ''):
    for i in a:
        for key, value in alphabet.iteritems():
            if i in key:
                yield value

print ''.join(answer('abdaac'))

Output:

>>> 100000110000100110100000100000100100

Comments

0

One way to manipulate printing in Python is to use the end parameter. By default it is a newline character.

print("foo")
print("bar")

will print like this:

foo
bar

In order to make these two statements print on the same line, we can do this:

print("foo",end='')
print("bar",end='')

This will print like this:

foobar

Hopefully this is a helpful way to solve problems such as this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.