robot man
robot man

Reputation: 31

How do i get every second word in a string including the first one?

Define a function called print_skip that accepts a string and prints out every second word in the string, starting with the first word. A word is treated as any sequence of letters that is separated from other letters by white space. You may assume a string is passed as a parameter.

thats the problem i'm having.

i tried to put it in a a list and index it from there and it works fine and passed most of the test that the website gives except one.

print_skip('Hello world!\nHow\nare\nyou!') and the excepted output is Hello How you. my code just crash when this happens

def print_skip(text):
only_letters = ''
new_words = []
for c in text:
    if(c.isalpha() or c==' '):
        only_letters += c
for x in only_letters.split():
    new_words.append(x)
for i in range(0,len(new_words)+1,2):
    print(new_words[i])

testing error

my code so far

this is the original question

Upvotes: 2

Views: 12324

Answers (3)

nathancy
nathancy

Reputation: 46650

You could use regex and re.sub to remove all non-alphabetic characters for each odd word in the string.

import re

def print_skip(text):
    if not text:
        return
    regex = re.compile('[^a-zA-Z]')
    for index, word in enumerate(text.split()):
        if index % 2 == 0:
            print(regex.sub('', word))

Method without using regex:

def print_skip(text):
    words = text.split()
    for index, word in enumerate(words):
        if not word.isalpha():
            clean_word = ''
            for i in range(len(word)):
                if word[i].isalpha():
                    clean_word += word[i]
            words[index] = clean_word
        if index % 2 == 0:
            print(words[index])

Upvotes: 0

Remy
Remy

Reputation: 160

Solution using for loop and modulo:

sentence = '1 2 3 4 5 6 7\n8 9 10'
words = sentence.split()
for i in range(len(words)):
    if i % 2 == 1:            # is true on uneven numbers, e.g. index 1, index 3, index 5
        print(words[i])

>>>2
>>>4
>>>6
>>>8
>>>10

This can be refactored down to a list comprehension as follow:

sentence = '1 2 3 4 5 6 7\n8 9 10'
words = sentence.split()
[print(words[i]) if i % 2 == 1 else None for i in range(len(words))]

Upvotes: 0

RockAndRoleCoder
RockAndRoleCoder

Reputation: 320

So strings in python actually let you index them like a list. Here's an example:

>>> myString = "How are You?  Where are you from?"

>>> breakUp = myString.split()

>>> breakUp[::2] #This 2 represents step size, so ever 2nd word will be called. 


['How', 'You?', 'are', 'from?']

Notice this includes the first word.

Appendum: So just using the split() here is not enough. I looked at the above example and the escape characters are in the string. I think a viable solution to dealing with escape characters inside your string are just replacting them with a ''. Here is an example:

myFixedString = "'Hello world!\nHow\nare\nyou!".replace('\n', ' ')
printSkip(myFixedString)

Upvotes: 4

Related Questions