【问题标题】:How can I end a string randomly and concatenate another string at the end in Python?如何在 Python 中随机结束一个字符串并在末尾连接另一个字符串?
【发布时间】:2010-02-17 05:44:57
【问题描述】:

基本上我有一个用户输入的字符串,例如:

“嗨,我叫鲍勃”

我想做的是让我的程序随机选择字符串的新结尾并以我指定的结尾结尾。

例如:

“你好,我叫 DUR。”

“嗨,mDUR。”

等等等等

我对python有点陌生,所以希望有一个简单的解决方案,呵呵

【问题讨论】:

    标签: python string concatenation


    【解决方案1】:

    类似这样的:

    import random
    
    s = "hi my name is bob"
    r = random.randint(0, len(s))
    print s[:r] + "DUR"
    

    字符串连接是使用+ 完成的。 [a:b] 表示法称为切片。 s[:r] 返回 s 的第一个 r 字符。

    【讨论】:

      【解决方案2】:
      s[:random.randrange(len(s))] + "DUR"
      

      【讨论】:

        【解决方案3】:

        不知道你为什么想要这个,但你可以做如下的事情

        import random
        user_string = 'hi my name is bob'
        my_custom_string = 'DUR'
        print ''.join([x[:random.randint(0, len(user_string))], my_custom_string])
        

        您应该阅读the docs 以了解random 模块,以了解您应该使用哪种方法。

        【讨论】:

          【解决方案4】:

          只是众多方法中的一种

          >>> import random
          >>> specified="DUR"
          >>> s="hi my name is bob"
          >>> s[:s.index(random.choice(s))]+specified
          'hi mDUR'
          

          【讨论】:

            【解决方案5】:

            您可以使用随机模块。请参阅下面的示例:

            import random
            s = "hi my name is bob"
            pos = random.randint(0, len(s))
            s = s[:pos] + "DUR"
            print s
            

            【讨论】:

              猜你喜欢
              • 2011-09-16
              • 1970-01-01
              • 2012-10-04
              • 1970-01-01
              • 2013-01-15
              • 1970-01-01
              • 2021-09-06
              • 2015-04-04
              • 2021-02-14
              相关资源
              最近更新 更多