Python splitting strings and jumbling the middle

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

提交回复
热议问题