簡體   English   中英

在python中將字符串轉換為int

[英]Converting string to int in python

a="1234"
for i in range(0,4):
            for k in range(i,4):
                s=int(a[i:k])
                print s

輸出:

Traceback (most recent call last):
  File "C:/Python27/Solutions/test.py", line 4, in <module>
    s=int(a[i:k])
ValueError: invalid literal for int() with base 10: ''

誰能告訴我為什么我得到這個錯誤? 我只想打印:1 12 123 1234 2 23 234,依此類推...

>>> a= "1234"
>>> a[0:0]   # in slice if start and end is same you will get empty string
''
>>> int(a[0:0])
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''
>>> 

我想你想要這個嗎?

>>> for i in range(3):
...     for k in range(i,4):
...         print int(a[i:k+1])
... 
1
12
123
1234
2
23
234
3
34

您收到此錯誤是因為循環的第一次迭代(i=0,k=0)需要a[0:0]='' (空字符串)。 字符和數字字符串可以轉換為整數,但是空字符串不是字符或字符串。 沒有字符。

如果要保護這種情況,則循環將隨后采用a的子字符串(example '123', i=0, k=3)並且可以將其轉換為整數123。其余情況應僅輸出所需的整數精細。

暫無
暫無

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

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