1

I've been trying to use .upper and .replace to turn non standard input like "helLo woRLD" to "HELLOWORLD" to make it easier to handle.

This seems so simple, and it works fine to turn it to uppercase, but it simply won't remove the spaces.

Code:

cmd = input("Please input a command: ")
cmd = cmd.upper()
cmd.replace(" ","")
print("%s" % (cmd))

With this, if I enter "Hello World" it would print "HELLO WORLD" with the spaces still there, and I have no idea why it's not working.

EDIT: This is embarrassing, I just realized a literally had to do

cmd = cmd.replace(" ","")

instead of what I had, flagging this because I figured it out

5
  • Strings are immutable in Python. Commented Mar 15, 2014 at 20:16
  • Hint: you need to create a new string. Commented Mar 15, 2014 at 20:18
  • Instead of flag, you can just accept the answer. :) Commented Mar 15, 2014 at 20:22
  • Why use multiple lines when a single one will do? :) print(input("Please input a command: ").upper().replace(" ","")) Commented Mar 15, 2014 at 20:34
  • Thank you for the 'embarressing' edit, It saved me some time :) Commented Mar 7, 2023 at 14:57

4 Answers 4

9

Strings in python are immutable. Instead of

cmd.replace(" ","")

say

cmd = cmd.replace(" ","")

You could also combine the two commands:

cmd = cmd.upper().replace(" ", "")
Sign up to request clarification or add additional context in comments.

Comments

0
cmd = input("Please input a command: ")
ans = cmd.upper().replace(" ","")
print("%s" % (ans))

Comments

0

This also works,but is not the best solution.

cmd="hello world"
print("%s" % ("".join(cmd.upper().split(" "))))

Comments

0
    while True :
        Word = input('enter string?')
        word = Word.strip()
        print(word)
        #this is the best option as far i am concerned to take input and 
        #removing  whitespaces
        #you can use this if you do not want to take any input
        #Word = 'string  of  a  thing  funny  ? '
        #word = Word.strip()
        #print(word)

Comments

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.