如何正确转换字符串而不是MutableString

时间:2011-04-16 17:38:59

标签: python

我试图将加密程序合并到聊天程序中。但是我不能用Socket传递一个MutableString。那么我如何将我的MutableString正确地转换为正确的字符串呢?

import sys
from UserString import MutableString

def GetMode():

while True:
    print '\n(E)ncrypt Or (D)ecrypt?'
    Mode = raw_input().lower()
    if Mode in 'e d encrypt decrypt'.split():
        return Mode
    else:
        print '\nEnter Proper Choice!'

def GetInput():
    while True:
        print '\n(T)ype Message Or (L)oad File?'
        Input = raw_input().lower()
        if Input in 't type'.split():
            Input = raw_input('>')
            return Input
        elif Input in 'l load'.split():
            MsgLoc = raw_input()
            MsgLoc = open(MsgLoc, 'r')
            try:
                Input = MsgLoc.read()
                MsgLoc.close()
                return Input
            except:
                print '\nCould Not Open' , MsgLoc
        else:
            print '\nEnter Proper Choice!'

def GetKey():
    while True:
        Key = 0
        print '\nPlease Enter A 20 Digit Number...\n** Do NOT use zeros!!!! EX-NAY ERO-ZAY! **'
        try:
            Key = int(input())
            Key = str(Key)
            if (len(Key) == 20):
                return Key
            else:
                print('\nPlease Enter A Valid Number!')
        except:
            print('\nPlease Enter A Valid Number!')

def Translate(Mode, Input, Key):
    if Mode[0] == 'e':
        print('\nEncrypting....')
        Encrypt(Input, Key)
    else:
        print('\nDecrypting....')
        Decrypt(Input, Key)

def Encrypt(Input, Key):
    Msg = MutableString()
    NonMutMsg = Input
    Msg += NonMutMsg
    MsgLen = len(Msg)
    CypherKey = Key
    a = 0
    b = 19

    #Loop For Proccessing Key
    for z in range(10):
        KeySkip = int(CypherKey[a])
        KeyIncrement = int(CypherKey[b])
        c = MsgLen/KeySkip
        d = -1

        #Loop To Skip Then Increment
        for y in range(c):
            d = d+KeySkip
            LtrNum = ord(NonMutMsg[d])
            LtrNum = LtrNum + KeyIncrement
            Msg[d] = chr(LtrNum)

1 个答案:

答案 0 :(得分:2)

首先,正如MutableString documentation所述:

  

应该注意的是,与真正的字符串或Unicode对象相比,这些类的效率非常低;对于MutableString尤其如此。

最重要的是:

  

本课程的主要目的是作为继承的教育范例

换句话说,不要在现实代码中使用此类。

要获取数据,请使用data参数:

pythonstring = mutablestring.data