如何划分字符串中包含 int 值和字符串值的一些字符串



是否可以在不依赖字符串索引的情况下将字符串(字符串内部有 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"

因为如果我使用切片,如果单词改变,代码将毫无用处,对吗?

我真的很好奇是否可以按类型划分,呵呵.. 谢谢你的帮助 😁

这应该可以完成这项工作

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]

最新更新