如何改组一串符号(即$,%,^)

时间:2015-03-28 04:45:15

标签: python

我需要创建一个" % % % "的字符串。这些空间也包括在内。每次运行代码时,我都需要随机放置%' s。所以它可以是"% % % "" %% %%"等。我已尝试使用random.shuffle(x),但它会出现错误消息TypeError: string indices must be integers。有没有其他方法可以将字符串洗牌?或者我该怎么做才能修复错误信息?

1 个答案:

答案 0 :(得分:0)

怎么样:

import random

# Create a list of characters, in this case 5 % and 5 spaces
l = ['%'] * 5 + [' '] * 5

# Shuffle it
random.shuffle(l)

# Create a string from the shuffled list
s = ''.join(l)
print(s)

或者,您可以使用输入字符串上的l调用结果初始化list()

l = list(" % % % ")

这就像l = ['%'] * 3 + [' '] * 4

如果其余代码相同,那么你就可以得到你想要的东西。