Stu
Stu

Reputation: 17

How do I remove the spaces when Python prints in for loop?

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().

Upvotes: 0

Views: 891

Answers (5)

Resin Drake
Resin Drake

Reputation: 546

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.

Upvotes: 0

Chiheb Nexus
Chiheb Nexus

Reputation: 9257

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

Upvotes: 0

marisbest2
marisbest2

Reputation: 1356

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)

Upvotes: 1

Mikael
Mikael

Reputation: 554

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.

Upvotes: 0

Dan
Dan

Reputation: 1884

brail = []
for i in str(...):
  if alphabet.get(i):
    brail.append(alphabet[i])
print ''.join(brail)

Upvotes: 0

Related Questions