1

I know that in Python, in order for the program to ignore space you can use input("something").strip() but what function do you use for the program to ignore the space if it's in the middle of the word like ja ck, also is there a way to combine the name, so if you enter it like ja ck it will print jack?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Acu
  • 85
  • 1
  • 7

4 Answers4

5

Replace the spaces with blank

>>> input("something\n").replace(' ','')
something
ja       ck
'jack'
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
3

You can use str.translate :

input("something").translate(None,' ') 

if you are in python 3 you need to do the following command:

input("something").translate({ord(' '):None})
Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • This is the user input syntax for Python3, but the `str.translate` syntax for Python2. You'll need to do `input("Something").translate(str.maketrans('', '', " "))` – Adam Smith Mar 25 '15 at 20:21
  • You can refer this http://stackoverflow.com/questions/17020661/why-doesnt-str-translate-work-in-python-3 – Bhargav Rao Mar 25 '15 at 20:25
  • (I always have to look it up to be sure. I know that in Python3 I can use `mapping = str.maketrans({oldlett:newlett for oldlett,newlett in replacements}); some_string.translate(mapping)` but I never remember how it goes together in Python2, so for any SO questions I double check to be sure. – Adam Smith Mar 25 '15 at 20:27
  • @AdamSmith ooops! yeah, sure ,thanks for reminding i'll edit the answer! – Mazdak Mar 25 '15 at 20:29
2

If you have a single word:

input("something").replace(" ","")

But foo bar will become foobar so it really depends on what input is possible, if you are taking more than a single word then it will be a very different proposition.

It might be better to get the user to confirm the input:

while True:
   inp = input("Please enter your").replace(" ","")
   confirm = input("You entered {}, enter "r" ro re-enter or any key to continue".format(inp))
   if inp == "r":
       continue
   else:
      # do whatever
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
1

you could also split the string on spaces, and reassemble it (without spaces):

 ''.join("ja ck".split())
umläute
  • 28,885
  • 9
  • 68
  • 122