0

I work on code which will give back all what user inserts. If user inserts secret_password then his next text after it should be formatted. Format of text should looks like:

john smith , JOHN SMITH , john , joh

john smithn + JOHN SMITH is easy and done below in the code.

Unfortunately, I don't know how to slice half part or other part of the string once the string can have other number of characters every time when user inserts something.

Could you please, suggest something. Code is done there is only missing slicing of the string.

print("Program echo v2!")
secret_password = "premium-code-2019"
text = ""
text_formatted = ""

while True:
    user_text = input()
    if user_text == secret_password:
        text = input("Insert the text")  
        text_formatted = text +" "+text.upper()      
        print(tekxt_formatted)
    elif user_text != secret_password:
        print(user_text)
    if user_text == "":
        break
Hubert S
  • 77
  • 7

2 Answers2

1

you can slice a string by using this method

string[len(string)//2:] #2nd half of the string

string[2:len(string)//2] #1nd half of the string 

string[:-1] string without the last charakter  
1

This should be fine:

print("Program echo v2!")
    secret_password = "premium-code-2019"
    text = ""
    text_formatted = ""
   
    while True:
        try:
            user_text = input()
            if user_text == secret_password:
                text = input("Insert the text")
                splitted = text.split(" ")
                text_formatted = "{}, {}, {}, {}".format(
                    text, text.upper(), splitted[0], splitted[0][:-1]
                )
                print(text_formatted)
            elif user_text != secret_password:
                print(user_text)
            if user_text == "":
                break
        except KeyboardInterrupt:
            break
Marco Valle
  • 176
  • 6
  • Marco I have one question. What is KeyboardInterrupt? Thanks for the code!!! – Hubert S Feb 01 '22 at 12:29
  • 1
    You’re welcome. KeyboardInterrupt exception occurs when you press Ctrl-C. If you write that exception handler, you can elegantly handle the exit from your program, otherwise the program terminates with an error, namely the KeyboardInterrupt error. Hope to has been clear. – Marco Valle Feb 01 '22 at 13:51
  • Thanks a lot for explanation it's clear for me :) – Hubert S Feb 02 '22 at 19:23