How can I remove whitespace from concatinated substring indexing in Python?

Question:

I’m working on a problem for a CS intro class. Though I’ve gotten it to work, I haven’t gotten it to work properly.

This is the assignment:
Write a program which reads a string using input(), and outputs the same string but with the first and last character exchanged. (You may assume the input string has length at least 2.) For example, on input Fairy a correct program will print yairF. Hint: use your solution to the previous program as part of the answer.

This is my code:

user_input = input()
print(user_input[len(user_input)-1],user_input[1:len(user_input)-1],user_input[0])

Unfortunately, my output is “y air F” instead of “yairF”. How would I be able to concatenate this indexing without the white-spaces? I’ve tried many things unsuccessfully and I haven’t been able to find anything in my search to help. I’m supposed to be able to make this happen using the len funtion, and indexing substrings.

Thank you in advance from a complete newb to Python!

Asked By: M Craft

||

Answers:

Just do :

user_input = input()
print(user_input[len(user_input)-1] + user_input[1:len(user_input)-1] + user_input[0])
#yairF

By default, when you use , in your print statement, it includes a whitespace after it. Here you are adding all the required strings, which you then pass to the print statement.


Or instead, you can use sep= to specify the seperator as an empty string.

print(user_input[len(user_input)-1],user_input[1:len(user_input)-1],user_input[0] , sep='')

And one more suggestion. Instead of doing user_input[len(user_input)-1] , you can directly do user_input[-1] which here will give you the last char.

Answered By: Kaushik NP

That’s because of the default behavior of print().

You can pass argument sep to override default seperator.

print(s1, s2, s3, sep='') this code will help you.

See the document in python interpreter with help(print)

Answered By: SungJin Steve Yoo