随机将字符串拆分为几个部分,并将结果添加到列表中

2024-04-20 13:28:15 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我有一个字符串,我想在一个随机的位置分裂。字符串的结果部分应添加到列表中, e、 g

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

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

如何实现以下目标:

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

我在考虑对字符串的字符进行迭代,但是如何实现“在随机位置拆分”的要求呢?你知道吗

事先非常感谢


Tags: 字符串代码gt列表google字符建议list
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:]]

您可以使用以下代码,并对其进行注释,以使您受益:

# 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)

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

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

相关问题 更多 >