【问题标题】:Shuffle string without shuffling the first and last char随机播放字符串而不随机播放第一个和最后一个字符
【发布时间】:2020-10-02 04:50:27
【问题描述】:

我试过了:

text="Sample sentence."
random.shuffle(text)
print(''.join(text))

但这会打乱一切,可能的输出:

nmactnpleSSe ee

我想要这样的东西:

Smplea ntesence.

【问题讨论】:

  • 您不能随机播放字符串 - 它们是不可变的。因此显示的输出与您发布的代码不对应。
  • text[0] + ''.join(random.shuffle(list(text[1:-1]))) + text[-1] 只要len(text) 大于 1。想法是保持 first 和 last 并在其间随机播放
  • 这能回答你的问题吗? How to scramble the words in a sentence - Python
  • @YossiLevi 您的shuffle 返回的不是None
  • 正确。这个绝对更好 - c = list(text[1:-1]);random.shuffle(c);print(text[1] + ''.join(c) + text[-1])。谢谢

标签: python


【解决方案1】:

只需提取并洗牌您想要的位,然后重新组装。

import random

text = "Sample sentence."

text1 = list(text[1:-1])
random.shuffle(text1)

text2 = text[0] + ''.join(text1) + text[-1]

print(text2)

注意:这回答了关于改组除第一个和最后一个字符之外的所有字符的问题。问题中显示的示例似乎是一种特殊情况,其中每个单词都被单独打乱。这是可能的结果,但不能保证。

【讨论】:

    【解决方案2】:

    见下文

    import random
    
    text = 'Sample sentence.'
    lst = [char for char in text[1:-1]]  
    random.shuffle(lst)
    lst.append(text[-1])
    lst.insert(0,text[0])
    print(''.join(lst))
    

    【讨论】:

      猜你喜欢
      • 2015-02-20
      • 2017-08-16
      • 2014-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-11
      • 2011-07-06
      相关资源
      最近更新 更多