-1

The question is this but I can not do string 5 reversing string. A sentence is to be encrypted as follows.

• The sentence is read in as a string, called string1.

• string2 is created using a loop. It is string1 without the spaces.

• string3 is created using a loop. It contains all the characters in string 1 plus a space after every four characters.

• string4 is created using a loop. Every character is replaced by the next one in the alphabet, and spaces are replaced by a “*” and “Z” or “z” is replaced by “A” or “a”

• string5 is created using a loop or nested loop (loop inside a loop). The characters in each group of four separated by “*” are reversed.

Eg If string1 = “The cat sat on the mat”

string2 = “Thecatsatonthemat”

string3 = “Thec atsa tont hema t”

string4 = “Uifd*butb*upou*ifnb*u”

string5 = “dfiU*btub*uopu*bnfi*u”

I have done this but string 5 does not work:

string1=str(input("Enter sentence: "))

string2=""

string3=""

string4=""

string5=""

count=0

for char in string1:

    if char==" ":

        string2=string1.replace(" ","")

    else:

        string2+=char


for char in string2:

    count+=1

    division=count%4

    if division==0:

        string3=string3+char+" "

    elif division!=0:

        string3=string3+char




for char in string3:

    newchar=""

    charnew="*"

    if char==" ":

        string4=string4+charnew

    else:

        newchar=chr(ord(char)+1)

        if newchar=="[":

            newchar="A"

        elif newchar=="{":

            newchar="a"

        string4=string4+newchar


#could not reverse the four letter sections but I reversed the whole string
rev=""        
for char in string4:
    rev=rev+char
    string5=rev[::-1]

print("string 1 = ",string1) 

print("string 2 = ",string2)

print("string 3 = ",string3)

print("string 4 = ",string4)

print("string 5 = ",string5)

This is what the I get when the program runs:

Enter sentence: The cat sat on the mat 

u*bnfi*uopu*btub*dfiU

string 1 =  The cat sat on the mat 

string 2 =  Thecatsatonthemat

string 3 =  Thec atsa tont hema t

string 4 =  Uifd*butb*upou*ifnb*u

string 5 =  u*bnfi*uopu*btub*dfiU

2 Answers2

3

Split and join:

s = "Hello World"

' '.join(i[::-1] for i in s.split(" "))

Output:

'olleH dlroW'
Anton vBR
  • 18,287
  • 5
  • 40
  • 46
1

You need to split the words and then reverse them

s = 'Hello World'
line = [w[::-1] for w in s.split()]

['olleH', 'dlroW']

To print it as a string, use print ' '.join(line)

Chen A.
  • 10,140
  • 3
  • 42
  • 61