如何分割一些字符串,字符串内部包含int值和字符串值。

问题描述 投票:0回答:1

是否可以将字符串(字符串内部有2种类型的可能性,例如字符串和整数)分割成2个东西,而不依赖于字符串的索引?例如,我想根据字符串的索引将其分割成两个东西。

# strings contain 2 possibilities, which is int and str
word = "123abc"

我想根据字符串的类型来分割字符串(如你所见,123可以变成整数类型,而abc cant则可以)。

# result that i want :  

integer = 123
strings = "abc"

但我不想用切片来做。我想根据他们的类型进行分析和划分。

# code that I don't want : 

integer = int(word[0:4])
# integer = 123
strings = word(word[4:])
# strings = "abc"

因为如果我用分片的话,如果字变了,代码就没用了吧?

我真的很好奇按类型划分到底可不可以这样嘿嘿......谢谢你的帮助😁。

python string types integer slice
1个回答
0
投票

这应该可以做到

word = '123abc'

# Create empty lists which you will append to later
integers = []
strings = []

# Go through every letter of the word
for i in word:
    # Try whether the character can be changed to an integer
    try:
        integer = int(i)
        # If so, append it to the integers list
        integers.append(integer)
    except:
        # If not, append it to the strings list
        strings.append(i)

print('strings:', strings)
print('integers:', integers)

这个指纹。

strings: ['a', 'b', 'c']
integers: [1, 2, 3]
© www.soinside.com 2019 - 2024. All rights reserved.