如何 scramble/shuffle/randomize python 中字符串的所有字母,除了第一个和最后一个字母?

How to scramble/shuffle/randomize all the letters of a string in python except the first and the last letter?

例如:

Example 1:
string = "Jack and the bean stalk."
updated_string = "Jcak and the baen saltk."
Example 2:
string = "Hey, Do you want to boogie? Yes, Please."
updated_string = "Hey, Do you wnat to bogoie? Yes, Palsee."

现在这个字符串存储在一个文件中。 我想从文件中读取这个字符串。并将更新后的字符串写回文件中相同的位置。 长度大于 3 的字符串的每个单词的字母必须是 scrambled/shuffled,同时保持首尾字母不变。此外,如果有任何标点符号,标点符号将保持原样。

我的做法:

import random
with open("path/textfile.txt","r+") as file:
    file.seek(0)
    my_list = []
    for line in file.readlines():
        word = line.split()
        my_list.append(word)

scrambled_list =[]
for i in my_list:
    if len(i) >3:
        print(i)
        s1 = i[1]
        s2 = i[-1]
        s3 = i[1:-1]
        random.shuffle(s3)
        y = ''.join(s3)
        z = s1+y+s2+' '
        print(z)

这是一种方法。

演示:

from random import shuffle
import string

punctuation = tuple(string.punctuation)

for line in file.readlines():   #Iterate lines
    res = []
    for i in line.split():      #Split sentence to words
        punch = False
        if len(i) >= 4:         #Check if word is greater than 3 letters
            if i.endswith(punctuation):    #Check if words ends with punctuation 
                val = list(i[1:-2])        #Exclude last 2 chars
                punch = True
            else:
                val = list(i[1:-1])        #Exclude last 1 chars
            shuffle(val)               #Shuffle letters excluding the first and last.
            if punch:
                res.append("{0}{1}{2}".format(i[0], "".join(val), i[-2:]))
            else:
                res.append("{0}{1}{2}".format(i[0], "".join(val), i[-1]))
        else:
            res.append(i)
    print(" ".join(res))