-1

I've finished writing the encryption code for Caesar cipher in Java and my plan is to rewrite the program using the same logic in Python as well. Although it can be done in many ways, is there any way I can use something equivalent to StringBuilder in Python? If I have a hold variable in Python that stores a string value then how can I append new characters or strings in a way similar done in Java below?

    static String encrypt(String s, int shift)
    {
        shift = shift % 26 + 26;
        StringBuilder hold = new StringBuilder();
        for (char i : s.toCharArray()) 
        {
            if (Character.isLetter(i)) 
            {
                if (Character.isUpperCase(i))
                    hold.append((char)('A' + (i - 'A' + shift) % 26 ));
                else
                    hold.append((char)('a' + (i - 'a' + shift) % 26 ));
            } 
            else
                hold.append(i);
        }
        return hold.toString();
    }
1
  • 1
    I think the question is fine (despite the close votes) although the question seems to boil down to "how to do string concatenation in python". Commented Nov 15, 2014 at 12:36

2 Answers 2

2

You can use direct list conversion of a string, and then use use the ord()/chr() functions to mess with an individual character's ASCII value.

Strings are immutable, but lists aren't. You can concatenate strings just fine in Python, and strings can be changed via list conversion and reconversion with split() and join().

Python strings also have isupper(), islower(), isdigit(), and isalpha() methods that give a boolean value.

I can't test this right now, because I don't fully understand your cipher, but I think it's close to replicating your JAVA code. You might want to tweak the cipher bits somewhat.

def encrypt(encryptString, shift):
    shift = shift % 26 + 26
    stringList = list(encryptString)
    for eachCharacter in stringList:
        if eachCharacter.isalpha() == True:
            if eachCharacter.isupper() == True:
                eachCharacter = chr( ( ord('A') + ord(eachCharacter) - ord('A') + shift) % 26)
            else:
                eachCharacter = chr( ( ord('a') + ord(eachCharacter) - ord('a') + shift) % 26)

    encryptString = ''.join(stringList)
    return encryptString
1

I would suggest using a list of characters i.e.

>>> x = ['a', 'b', 'c']
>>> x
['a', 'b', 'c']
>>> x.append('d')
>>> x += ['e', 'f']
>>> x
['a', 'b', 'c', 'd', 'e', 'f']
>>> "".join(x)
'abcdef'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.