您可以定義自己的split()
版本。我在這裏命名爲my_split()
。
def my_split(astring):
return [find_type(x) for x in astring.split()]
def find_type(word):
try:
word_type = int(word)
except ValueError:
try:
word_type = float(word)
except ValueError:
word_type = word
return word_type
a = 'Hello I have 4 ducks weighing 3.5 kg each'
split_type = [x for x in my_split(a)]
print(split_type)
#['Hello', 'I', 'have', 4, 'ducks', 'weighing', 3.5, 'kg', 'each']
print([type(x) for x in my_split(a)])
#[<class 'str'>, <class 'str'>, <class 'str'>, <class 'int'>, <class 'str'>, <class 'str'>, <class 'float'>, <class 'str'>, <class 'str'>]
for i, word in enumerate(split_type):
if type(word) == int:
print('Integer found at position {:d}'.format(i + 1))
# Returns: 'Integer found at position 4'
你看過其他的字符串方法嗎? 'str.isdigit'可能會有所幫助。或者你可以'嘗試'轉換爲整數並處理諸如'鴨子'之類的事情? – jonrsharpe
所以,有一個metod像split()那樣工作,但能夠識別每個部分的類型? str.isdigit會這樣做嗎?謝謝 –
不,沒有。你將不得不自己實現這個功能,但有一些有用的方法可以相對簡單地完成它。 – jonrsharpe