簡體   English   中英

從整數中提取值

[英]Extracting a value from an integer

假設我在Python中的值是9010,如何從9000中增加數字10,然后將10賦給變量,例如b = 10。

干杯。

為此,我將遠離字符串操作:

>>> a = 9010
>>> 
>>> b = a % 100
>>> 
>>> b
10

這是提取整數的最后兩位數字的簡單方法:

n = 9010

int(str(n)[-2:])
=> 10

使用類似的想法,您可以從數字中提取任何數字序列,方法是先將其轉換為字符串,然后通過擺弄索引來提取所需的數字范圍。

我看到的最簡單的方法是將其轉換為字符串並提取最后兩個字母。 像這樣:

a = 9010 # This is a integer.
b = str(a)[-2:] # str() converts to a string, and [-2:] returns the last two letters of the string.

b # Checking its value.
=> '10' # Now this is a string, if you want it to be a integer use the int() function.

b = int(b) # The old value of b is converted into an integer and saved back into b.
b # Checking its new value.
=> 10 # b is now an integer.

b將是字符串“ 10”。 因此,將其用作整數,只需使用int()函數將其轉換即可。 例如int(b)

暫無
暫無

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

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