【问题标题】:How to divide some string that inside of strings contain int value and string value如何划分字符串内部包含int值和字符串值的一些字符串
【发布时间】:2020-10-03 02:13:07
【问题描述】:

是否可以在不依赖字符串索引的情况下将字符串(字符串内部有 2 种类型可能性,例如字符串和整数)拆分为 2 种事物?例如:

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

我想根据它们的类型来划分字符串(如您所见,123可以更改为整数类型和abc不能)

# 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】:

    这应该可以完成工作

    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]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多