简体   繁体   中英

How do I make a 'while' loop print the results of the loop's conditional into a single line(concatenated)?

So here is my code:

test = {
    'a':1, 'b':2 , 'c':3 , 'd':4
}

x = raw_input("Type 'abcd' ")
y = len(x)
z = 1
while z < y+1:
    a = x[z-1]
    print test[a]
    z = z + 1

The point is to make a basic encoder, obviously this code is just to establish a quasi-code that I can build off of. My issue is this:

I can't make the result of the 'while' loop print into a single line, and with that, not only print into a single line, but to concatenate into a larger integer(or string for that matter, say the result of the code displayed letters instead of integers, to create a string from those letters). Although, in this code specifically, I want the result of the code to be the integer ' 1234 '. Not:

1
2
3
4

Essentially, my question is this: How do I make the results of a while loop print in such a way that they concatenate integers(or letters) to create a larger number(or string)? I don't want the result 1 2 3 4

to become 10, but instead I want it to become the integer 1234 . I've looked online, but I can't find anything that works for me. In fact I haven't found anything at all.

First of all, using a while loop here isn't optimal, instead, use a for loop, which is designed to loop over iterators like data structures (a string is just a sequence of characters):

for character in x:
    print(test[character])

Then instead of printing the characters, store them in a list.

characters = []
for character in x:
    characters.append(str(test[character]))

We can then join those into a single string (we made the numbers strings earlier to make this step easier), and make an int from that string:

int("".join(characters))

Python supports an easier way to do this kind of list construction - the list comprehension :

characters = [str(test[character]) for character in x]

This produces the same list as the for loop above, but faster and more concisely.

This means we can write your program as:

test = {'a': 1, 'b': 2 , 'c': 3 , 'd': 4}

user_input = raw_input("Type 'abcd':")

number = int("".join(str(test[character]) for character in user_input))

As an alternative to making the numbers strings to concatenate, then reverting back, we could also do it with maths:

number = sum((10 ** power) * test[character] 
             for power, character in enumerate(reversed(user_input)))

What we do here is start from the right, take each number, multiply it up by the power of ten for the column it is in, and then sum the lot.

The easy answer is: don't print within the while loop, but concatenate up a string to print at the end:

result = ''
while z < y+1:
    a = x[z-1]
    result += str(test[a])
    z = z + 1
print result

If there are going to be a whole bunch of things, instead of concatenating strings on the fly, use a list and join at the end:

result = []
while z < y+1:
    a = x[z-1]
    result.append(str(test[a]))
    z = z + 1
print ''.join(result)

But you say you want to get an integer. Do you need that integer, for any reason other than to print it out? If so, you could build up a string and then convert it to an integer:

result = []
while z < y+1:
    a = x[z-1]
    result.append(str(test[a]))
    z = z + 1
val = int(''.join(result))

But this is silly. Why not just build up the value as an integer in the first place?

val = 0
while z < y+1:
    a = x[z-1]
    val = val * 10 + test[a]
    z = z + 1

Since you seem to be using Python 2, the only way to print without adding a newline, instead adds a space, which doesn't help. But Python 3—and Python 2 with from __future__ import print_function —has a more flexible alternative:

while z < y+1:
    a = x[z-1]
    print(test[a], end='')
    z = z + 1
print()

Or you can write directly to stdout :

while z < y+1:
    a = x[z-1]
    sys.stdout.write(str(test[a]))
    z = z + 1
sys.stdout.write('\n')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM