简体   繁体   中英

Remove white space from list output

The code I have written is to produce the fibonacci series to the point chosen by the user, for example '10' will produce:

[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

The problem is the empty space, I was wondering if it was possible to get it to print like this instead:

[1,1,2,3,5,8,13,21,34,55]

without the spaces.

This is the code I'm using:

a=int(input("write the length of numbers you would like to see the fibonacci series for(by entering 0 or 1 the output will be [1,1]):  "))

if a<0:
     print("invalid entry please type a positive number")
else:        
    i=2
    fibs=[1,1]
    b=fibs[-2]
    c=fibs[-1]
    d=b+c
    while i<a :
        i=i+1
        b=fibs[-2]
        c=fibs[-1]
        d=b+c
        fibs.append(d)
print(fibs)

When you print a container like that, its use of whitespace is already decided in it's __repr__ method. You'll have to format the output yourself:

print('[{}].format('",".join(map(str, fibs))))  # Instead of print(fibs).

This code:

print('[{}]'.format(','.join([str(x) for x in fibs])))

Creates a new list made up of your numbers converted to strings, joins it with a comma and prints it between braces.

Please note that this is not the fastest and easiest way to do what you want.

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