Home > Mobile >  Why is strip() not working with input in a function then being printed?
Why is strip() not working with input in a function then being printed?

Time:09-27

Yes, I do realize that this question has been asked many, many times, but on looking through those answers none seemed to answer my question. If you know of one that dose, link it for me and I will read it but I couldn't find one.

I have a function called question

def question():
   return input("What is the answer \n\t")

Then, when I try to strip and print the function it dose not strip:

answer=question()
answer=answer.strip()
print(".", answer, ".")

The output is . answer . (Not the word answer, the variable answer. What am I doing wrong?

CodePudding user response:

Looks like you want the 'sep' argument in your print statement. The 'sep' argument tells the print function what to place between each string argument sent to it. By default this is a single space ' '. But if you do this, then there will be no characters between string arguments.:

print('.', answer, '.', sep='')

This will output the line that you want. But you could also make use of the format method to do this a little cleaner:

print('.{}.'.format(answer))

or

print(f'.{answer}.')

CodePudding user response:

If by "Not working" you mean the space between "." and answer's value, that's because of the way you are printing it. try this

print(".{}.".format(answer))

CodePudding user response:

You can define the seperator of the print function

print('.',answer,'.', sep='')

or use an f string

print(f".{answer}.")

CodePudding user response:

Use, one of the below,

print('.', answer, '.', sep='')
print('.{}.'.format(answer))
print(f'.{answer}.')

The first one defines the sep as '' or nothing so no space is put between the words.

The basic idea of the other two is that the {} is replaced with the value of the variable answer.

  • Related