【问题标题】:Splitting a string at random position and adding resulting parts to a list在随机位置拆分字符串并将结果部分添加到列表中
【发布时间】:2020-01-31 03:33:03
【问题描述】:

我刚开始使用 Python 编码,遇到了一些我认为很容易解决的问题(至少在 Google 的帮助下...):

我有一个要在随机位置拆分的字符串。字符串的结果部分应添加到列表中, 例如

str = "abcdefg" 应该变成-->list = ["abc","defg"]

在此示例中,建议我在字符串中确定一个随机分隔符(使用 randrange),在此分隔符处拆分并将各个部分放在一起。 效果很好,我理解了代码并且能够稍微修改它。 但是,当字符串多次包含一个字符时,由于固定分隔符,此方法会在每次出现时剪切。

如何实现以下目标:

str = "abcdabcd" --> list = ["abc","dabcd"]?

我正在考虑迭代字符串的字符,但是我将如何实现“在随机位置拆分”的要求?

提前非常感谢您

【问题讨论】:

    标签: python string list random split


    【解决方案1】:

    您可以使用以下代码,注释对您有利:

    # Use the random module to create a random number
    import random
    # Copy your test string
    myStr = "abcdabcd"
    # The highest value the random number could be is the length of the string
    max_random = len(myStr)
    # Create the random value using the random module
    random_val = random.randrange(max_random)
    
    # Create your new list by splitting the string first by:
    # all characters up to the random value, then from the random value onwards
    new_list = [myStr[:random_val], myStr[random_val:]]
    
    # This is an example of splitting the string after 3, which you describe in your question
    example_list = [myStr[:3], myStr[3:]]
    
    
    # print it out
    print(new_list)
    print()
    print(example_list)
    

    【讨论】:

      【解决方案2】:

      您可以在随机选取的索引处对字符串进行切片:

      import random
      s = "abcdabcd"
      i = random.randrange(len(s))
      print([s[:i], s[i:]])
      

      【讨论】:

        【解决方案3】:

        您可以通过切片和使用random.randint 来拆分它:

        import random
        my_str = 'somestring'
        random_index = random.randint(0, len(my_str)-1)
        my_list = [my_str[:random_index], my_str[random_index:]]
        

        【讨论】:

        • randint 返回一个整数,其中可以包含停止数字,在这种情况下,它会超出范围。
        • @blhsing 你是对的,添加了一个 -1 来适应它
        猜你喜欢
        • 2018-01-15
        • 2018-04-23
        • 2018-07-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-16
        • 2022-01-22
        • 1970-01-01
        相关资源
        最近更新 更多