Reputation: 1
I have an assignment for programming, and I'm having trouble. I'm 99% done but it's the little things that are tripping me up. Here is my code:
a = 0
b = 0
c = 0
for h in first:
a = LetterMap[h]
print(a,end="")
for h in middle:
b = LetterMap[h]
print(b,end="")
for c in last:
c = letterMap[c]
print(c,end="")
The output before this block and this block is this:
first middle last
xxxxxxxxxxxxxxx
I would like it to be this:
first middle last
xxxxx xxxxxx xxxx
Upvotes: 0
Views: 259
Reputation: 104712
Rather than printing out your characters one by one, I'd suggest using str.join
and generator expressions to combine your translated sequences into strings:
first_str = "".join(LetterMap[c] for c in first)
middle_str = "".join(LetterMap[c] for c in middle)
last_str = "".join(LetterMap[c] for c in last)
Then you can print them with just one print
call:
print(first_str, middle_str, last_str) # default separator is a space!
If you wanted some more sophisticated formatting of the output (rather than just spaces separating the values), you can use the str.format
method to do whatever kind of formatting you want:
print('{2:<20}{1:_^20}{0!r:*>20}'.format(first_str, middle_str, last_str)
That will print the strings in "reverse" order, with the "last" one left-justified in a width-20 column, the middle value centered in a width-20 column with underscores padding it on each side, and a representation of the "first" value (with quotes and backslash escapes, as needed) on the right of the final 20-wide column padded with asterisks.
For example, if you three strings were 'foo'
, 'bar'
and 'baz'
, you'd get:
baz ________bar_________***************'foo'
You can read about the string formatting mini-language in the documentation.
Upvotes: 0
Reputation: 10014
Try this:
for h in first:
a = LetterMap[h]
print(a,end="")
print(" ",end="")
for h in middle:
b = LetterMap[h]
print(b,end="")
print(" ",end="")
for c in last:
c = letterMap[c]
print(c,end="")
Upvotes: 1