Change string to uppercase and remove whitespace

5

I'm trying to make a program in Python 3 that should turn typed text into uppercase and remove white space. I would like to know what is wrong with my code since it is not deleting the blanks. I tested two codes.

  • First code:

    print ("-"*50)
    print ("-"*50)
    
    frase = input("\nEscreva uma frase: ")
    
    frase = frase.upper()
    frase = frase.strip()
    
    print ("\n",frase)
    
    
    print ("-"*50)
    print ("-"*50)
    
  • Second Code

    print ("-"*50)
    print ("-"*50)
    
    frase = input("\nEscreva uma frase: ")
    
    frase = frase.upper()
    frase = frase.replace('','')
    
    print ("\n",frase)
    
    print ("-"*50)
    print ("-"*50)
    
asked by anonymous 31.10.2018 / 12:02

2 answers

7

The first one only takes spaces from the beginning and end, the middle would be the second code, but it is not changing anything, the code has to change nothing for nothing, that is, it does not move, it has to be space for nothing: p>

frase = input("Escreva uma frase: ")
frase = frase.upper().replace(' ','')
print("\n", frase)

See running on ideone . And no Coding Ground . Also I placed GitHub for future reference .

But if it is an exercise maybe the goal would be to do in hand, character by character without using function ready. What could even have more performance eventually because in the current form has to move twice in the same string , with a single loop can change the character and withdraw space at the same time. So:

frase = input("Escreva uma frase: ")
fraseNova = ""
for chr in frase:
    if chr != " ":
        fraseNova += chr.upper()
print(fraseNova)

See running ideone . And no Coding Ground . Also put it in GitHub for future reference .

    
31.10.2018 / 12:12
2

The method str.strip() removes characters only from the beginning and the end of a string.

string = "     a     b     ".strip()
print(string);  # 'a     b'

The str.replace() method receives as the first parameter a search string and as second parameter a substitution string. The method will replace all occurrences * of the search string with the replacement string.

string = "     a     b     ".replace(' ', '-')
print(string);  # "-----a-----b-----"

* The 3rd parameter defines the maximum amount of substitution the method will make. If not specified, all occurrences will be overwritten. [docs]

So your second code is wrong just because you are asking to search for nothing ( '' ) and substituting for nothing ( '' ). When you want to search for spaces ( ' ' ) and replace them with nothing ( '' ).

As Maniero has already replied, your code would look something like:

frase = input('...')
frase = frase.upper().replace(' ','')
print(frase)
    
31.10.2018 / 12:56