簡體   English   中英

我被告知要反轉 python 中的一個數字我這樣做了,但我不能在最后一個元素之后刪除逗號

[英]I was told to reverse a number in python I did that but I can't remove comma after the last element

num=32768
x=0
y=0
while x<num:
    x=num%10
    y=num//10
    num=y
    print(x,end=',')

這是我的代碼 output 顯示 8,6,7,2,3,現在如何刪除 3 后的逗號?

將數字放入列表中,然后使用join()打印帶有逗號分隔符的列表。

num=32768
x=0
y=0
result = []
while x<num:
    x=num%10
    y=num//10
    num=y
    result.append(str(x))
print(",".join(result))

你可以在一行中做到這一點:

 ",".join(str(32768)[::-1])

使用三元運算符,例如:

num = 32768
x = 0
y = 0
while x < num:
    x = num % 10
    y = num // 10
    num = y
    print(x, end=',' if x < num else '')

只需添加一個條件來檢查您是否已到達最后一個號碼。

num=32768
x=0
y=0
while x<num:
    x=num%10
    y=num//10
    num=y
    if x >= num: 
        print(x, end='')
    else:
        print(x,end=',')


一種更簡單的方法(假設您沒有明確禁止這樣做)是將整數轉換為字符串,然后將其反轉。

>>> num = 32768
>>> print(str(num)[::-1])
86723
>>> print(','.join(str(num)[::-1]))
8,6,7,2,3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM