Python splitting strings and jumbling the middle

后端 未结 2 457
旧巷少年郎
旧巷少年郎 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

    0 讨论(0)
  • 2021-01-15 20:33

    You can use shuffle from the random package:

    import random
    letters = list(still_to_scramble)
    random.shuffle(letters)
    scrambled = ''.join(letters)
    

    Here's how it would work:

    >>> s
    '$123abc$'
    >>> first_letter = s[0]
    >>> last_letter = s[-1]
    >>> middle_parts = list(s[1:-1])
    >>> random.shuffle(middle_parts)
    >>> ''.join(middle_parts)
    'b3a2c1'
    

    Be careful and don't do this:

    >>> middle_parts_random = random.shuffle(middle_parts)
    

    shuffle works in place - that's a fancy way of saying it does't return the shuffled bit, but modifies it instead. It actually returns None, and you may get tripped up by it, since you won't see an error:

    >>> middle_parts_random = random.shuffle(middle_parts)
    >>> middle_parts_random # Huh? nothing is printed!
    >>> middle_parts_random == None # Ah, that's why. Darn you in-place methods!
    True
    
    0 讨论(0)
提交回复
热议问题