Python splitting strings and jumbling the middle

后端 未结 2 456
旧巷少年郎
旧巷少年郎 2021-01-15 20:06

I am having trouble with a program in python...I need the program to jumble the middle of words while keeping the outer two letters intact...I believe I have successfully sp

2条回答
  •  囚心锁ツ
    2021-01-15 20:29

    I've added a regular expression to extend Burhan Khalid's solution above. This addition works for input with multiple words which I think some might find useful.

    $ cat ./jumble.py
    #!/usr/bin/env python
    import re
    import random
    
    def jumble(s):
        l = list(s)
        random.shuffle(l)
        return(''.join(l))
    
    line = raw_input("Input string to jumble: ")
    print(re.sub(r'\b(\w)(\w+)(\w)\b', lambda m: "".join([m.group(1),jumble(m.group(2)),m.group(3)]), line))
    

    For example:
    $ ./jumble.py
    Input string to jumble: I am just entering some arbitrary string
    I am jsut etnrneig some aabtrrriy sritng

    Note: The above example was done on a Red Hat Enterprise Linux 6.7 system with the default python-2.6.6-64.el6.x86_64

提交回复
热议问题