-2

I am trying to build a function that will take a string and print every other letter of the string, but it has to be without the spaces.

For example:

def PrintString(string1):
    for i in range(0, len(string1)):
        if i%2==0:
            print(string1[i], sep="")

PrintString('My Name is Sumit')

It shows the output:

M
 
a
e
i
 
u
i

But I don't want the spaces. Any help would be appreciated.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • It is unclear whether you do not want the spaces in the output or you just want to ignore the spaces before picking every other character. – norok2 Sep 08 '20 at 08:05
  • I don't want the spaces in the output –  Sep 08 '20 at 08:07
  • 1
    then just update the condition in the `if` to reflect what you do not want to print, e.g. `if i % 2 == 0 and string1[i] != ' ':` – norok2 Sep 08 '20 at 08:09
  • Does this answer your question? [Remove all whitespace in a string](https://stackoverflow.com/questions/8270092/remove-all-whitespace-in-a-string) – JE_Muc Sep 08 '20 at 08:10
  • `sep=""` does nothing in your code. Did you mean `end=""`? – Wups Sep 08 '20 at 08:21

5 Answers5

1

Use stepsize string1[::2] to iterate over every 2nd character from string and ignore if it is " "

def PrintString(string1):
    print("".join([i for i in string1[::2] if i!=" "]))

PrintString('My Name is Sumit')
Sociopath
  • 13,068
  • 19
  • 47
  • 75
1

Remove all the spaces before you do the loop.

And there's no need to test i%2 in the loop. Use a slice that returns every other character.

def PrintString(string1):
    string1 = string1.replace(' ', '')
    print(string1[::2])
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

Replace all the spaces and get every other letter

def PrintString(string1):
  return print(string1.replace(" ", "") [::2])

PrintString('My Name is Sumit')
Wimanicesir
  • 4,606
  • 2
  • 11
  • 30
0

It depends if you want to first remove the spaces and then pick every second letter or take every second letter and print it, unless it is a space:

s = "My name is Summit"
print(s.replace(" ", "")[::2])
print(''.join([ch for ch in s[::2] if ch != " "]))

Prints:

MnmiSmi
Maeiumt
Maciek
  • 762
  • 6
  • 17
-1

You could alway create a quick function for it where you just simply replace the spaces with an empty string instead. Example

def remove(string): 
    return string.replace(" ", "") 

There's a lot of different approaches to this problem. This thread explains it pretty well in my opinion: https://www.geeksforgeeks.org/python-remove-spaces-from-a-string/

Zelcus
  • 30
  • 6