简体   繁体   中英

Printing every other letters of a string without the spaces on Python

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.

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')

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])

Replace all the spaces and get every other letter

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

PrintString('My Name is Sumit')

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM