Using split function without split() string method. Almost - python

I'm trying to replicate the .split() string method. It works well but it doesn't include the last word.
def stringSplitter(string):
words = []
current_word = ""
for x in range(len(string)): #problem is here
if string[x] == " ":
words.append(current_word)
current_word = ""
else:
current_word += string[x]
return words
Test 1: When sentence=I like to ride my bicycle, my code incorrectly outputs:
['I', 'like', 'to', 'ride', 'my']
The result I want is:
['I', 'like', 'to', 'ride', 'my', 'bicycle']

Add words.append(current_word) just before returning from the function. That's your "lost" word. Also, there is no need to use either range or any indexing. for x in string: iterates directly over the characters.

Note this could be implemented more succinctly using a generator function - if you didn't mind deviating from the "real" str.split() function implementation a little bit:
>>> def split(string, delimiter=' '):
current_word = ''
for char in string:
if char == delimiter:
yield current_word
current_word = ''
else:
current_word += char
yield current_word
>>> list(split('I like to ride my bicycle'))
['I', 'like', 'to', 'ride', 'my', 'bicycle']
>>>
You could even modify it to allow returning the delimiter as well:
>>> def split(string, delimiter=' ', save_delimiter=False):
current_word = ''
for char in string:
if char == delimiter:
yield current_word
if save_delimiter:
yield char
current_word = ''
else:
current_word += char
yield current_word
>>> list(split('I like to ride my bicycle', save_delimiter=True))
['I', ' ', 'like', ' ', 'to', ' ', 'ride', ' ', 'my', ' ', 'bicycle']
>>>

I got it with the help of the first answer by #DYZ. Thank you! Apparently, I was skipping the last word because I need to add (below) before the return.
words.append(current_word)
My Code:
def stringSplitter(string):
words = []
current_word = ""
for char in string:
if char == " ":
words.append(current_word)
current_word = ""
else:
current_word += char
words.append(current_word)
return words

Related

How to output a sentence or phrase with no whitespace?

This is an assignment where we have to take a sentence or phrase as input and output the phrase without whitespace.
Example: if input is 'hello there'
output would be 'hellothere'
the code I have so far only outputs the string in separate letters: Like 'h', 'e', 'l', etc etc
def output_without_whitespace(input_str):
lst = []
for char in input_str:
if char != ' ':
lst.append(char)
return lst
if __name__ == '__main__':
phrase = str(input('Enter a sentence or phrase:\n'))
print(output_without_whitespace(phrase))
def output_without_whitespace(input_str):
str1=input_str.replace(" ","")
return str1
if __name__ == '__main__':
phrase = str(input('Enter a sentence or phrase:\n'))
print(output_without_whitespace(phrase))
You've almost got it. You just need to join the list into a string.
print(''.join(output_without_whitespace(phrase)))
You could replace the loop in your function with a list comprehension.
def output_without_whitespace(input_str):
return [ch for ch in input_str if ch != ' ']
That will return the same list your implementation does.
If you want your function to return a string, we can use the same join from before:
def output_without_whitespace(input_str):
return ' '.join([ch for ch in input_str if ch != ' '])
But if we're doing that, we don't really need to pass a list to join. Instead we can use a generator expression.
def output_without_whitespace(input_str):
return ' '.join(ch for ch in input_str if ch != ' ')
As others have pointed out, all of this is overkill if we just use replace.
def output_without_whitespace(input_str):
return input_str.replace(' ', '')
def output_without_whitespace(phrase):
return phrase.replace(" ", "")
if __name__ == '__main__':
phrase = str(input('Enter a sentence or phrase:\n'))
print(output_without_whitespace(phrase))
Reference: https://stackoverflow.com/a/8270146/17190006

python linux search a word start with a word

I want to have a method that return true when a string contain a certain word example i want the word musique and i want to check it with "musique.txt" i want to return true because "musique.txt" contain the word musique
def contains_word(contain, word):
print((' ' + word + ' ') in (' ' + contain + ' '))
return (' ' + word + ' ') in (' ' + contain + ' ')
contains_word('musique.txt', 'musique') # True
contains_word('musique1.txt', 'musique') # False
This would work:
def contains_word(contain, word):
with open(contain,'r') as f:
text = f.readlines()
for i in text:
temp = i.split()
for j in temp:
if word == j:
return True
return False
contains_word('musique.txt', 'musique')
Basically in this code, each and every word is matched against the provided word.

How to Find words before and after keyword in python without inbuilt method

I want to find the word before and after the keyword wihtout using inbuilt method
code is working fine with partition method
mystring = "This is python class"
keyword = ' is'
before_keyword, keyword, after_keyword = mystring.partition(keyword)
l = []
l.append(before_keyword)
l.append(keyword)
l.append(after_keyword)
print(l)
My output and expected out is below
['This', ' is', ' python class']
Sample input for testing
input >> "This hello is to test"
keyword >> ' is'
Expected out >> ['This hello', 'is', 'to test']
You could try using insert and split as follows:
mystring = mystring.split(keyword)
mystring.insert(1, keyword)
print(mystring)
Output:
['This', ' is', ' python class']
Edit:
To make the code work with every kind of string, you can use this massive code:
mystring = "This is python class and it is a unicorn"
keyword = 'is'
newlist = []
if keyword in mystring:
string = ''
for i in mystring.split():
if i == keyword:
newlist.append(string)
newlist.append(i)
string = ''
else:
string += i + ' '
newlist.append(string)
newlist = [i.strip() for i in newlist if i]
print(newlist)
Output:
['This', 'is', 'python class and it', 'is', 'a unicorn']
with no functions. just string compare using ==
If you are not allowed to use any builtin function, then one of the option is to do string compare. I assume you cannot use len() builtin function as well.
mystring = "This is python class and it is a unicorn"
keyword = 'is'
list_of_words = []
word = ''
key_len = str_len = 0
#to get length of keyword as you cannot use len(keyword)
for _ in keyword: key_len +=1
for _ in mystring: str_len +=1
i = 0
start_pos = 0
if keyword in mystring:
while i < str_len:
if mystring[i:i+key_len] == keyword:
if i != 0:
list_of_words.append(mystring[start_pos:i])
list_of_words.append(keyword)
i += key_len
start_pos = i
else:
i+=1
if start_pos != str_len and start_pos != 0:
list_of_words.append(mystring[start_pos:])
if list_of_words:
print (list_of_words)
else:
print (keyword, 'is not found in', mystring)
Output is as follows:
Input words:
mystring = "This is python class and it is a unicorn"
keyword = ' is'
Output:
['This', ' is', ' python class and it', ' is', ' a unicorn']
Input words:
mystring = "This is python class and it is a unicorn"
keyword = ' unicorn'
Output:
['This is python class and it is a', ' unicorn']
Input words:
mystring = "This is python class and it is a unicorn"
keyword = ' as'
Output:
as is not found in This is python class and it is a unicorn
Input words:
mystring = "This is python class and it is a unicorn"
keyword = 'This'
Output:
['This', ' is python class and it is a unicorn']
use find function
You can search for the keyword and create the list as follows:
mystring = "This is python class"
keyword = ' as'
l = []
x = mystring.find(keyword)
if x != -1:
l.append(mystring[:x])
l.append(keyword)
l.append(mystring[x+len(keyword):])
print (l)
else:
print (keyword, 'is not found in', mystring)
Assuming that you don't want to use in-built methods, you can create your own partition or not_partition :P
inp = "This hello is to test"
def not_partition(inp='', part_at=''):
inp = inp.strip().split()
ret = ['']
for i,v in enumerate(inp):
if v==part_at:
ret = ret+[part_at, '']
else:
ret[-1] = (ret[-1]+' '+v).strip()
if ret[-1]=='': del ret[-1]
return ret
not_partition(inp, 'is'), not_partition(inp, 'test')
['This hello', 'is', 'to test'], ['This hello is to', 'test']
You can also create a more efficient recursive not_partition :D
def not_partition(inp='', part_at=''):
inp = inp.strip().split()
i=0
while i<len(inp):
if inp[i]==part_at:
return [' '.join(inp[:i]), part_at]+not_partition(' '.join(inp[i+1:]),part_at)
else:
i+=1
return [' '.join(inp)] if inp!=[] else []
not_partition(inp, 'is'), not_partition(inp, 'test'), not_partition(inp, 'what?')
['This hello', 'is', 'to test'],
['This hello is to', 'test'],
['This hello is to test']
You can also try using regex for this problem
import re
keyword = 'is'
str1 = "This hello is to test"
partition = re.split(r'\s({0})\s'.format(keyword), str1)
partition
['This hello', 'is', 'to test']

Answer not accepted for codewards --- but my output matches their desired output

This is the kata:
From https://www.codewars.com/kata/5264d2b162488dc400000001/train/python
Write a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed (Just like the name of this Kata). Strings passed in will consist of only letters and spaces. Spaces will be included only when more than one word is present.
Examples: spinWords( "Hey fellow warriors" ) => returns "Hey wollef sroirraw" spinWords( "This is a test") => returns "This is a test" spinWords( "This is another test" )=> returns "This is rehtona test"
This is my code:
def spin_words(sentence):
sentence_array = sentence.split()
new_array = []
for word in sentence_array:
if len(word) >= 5:
word = word[::-1]
new_array.append(word)
else:
new_array.append(word)
new_sentence = ''
for word in new_array:
new_sentence += word + ' '
return new_sentence
Having trouble figuring out why it isn't being accepted
The problem with your code is that the returned strings will have a trailing whitespace. Remove them by using a slice of [:-1]:
def spin_words(sentence):
sentence_array = sentence.split()
new_array = []
for word in sentence_array:
if len(word) >= 5:
word = word[::-1]
new_array.append(word)
else:
new_array.append(word)
new_sentence = ''
for word in new_array:
new_sentence += word + ' '
return new_sentence[:-1]
For a cleaner and more efficient approach:
def spin_words(sentence):
word_array = sentence.split()
spin_array = [word[::-1] if len(word) > 4 else word for word in word_array]
new_sentence = ' '.join(spin_array)
return new_sentence
You are printing additional space at the end which is wrong.
def spin_words(sentence):
sentence_array = sentence.split()
new_array = []
for word in sentence_array:
if len(word) >= 5:
word = word[::-1]
new_array.append(word)
else:
new_array.append(word)
return ' '.join(new_array)
I found an answer to get it to pass:
def spin_words(sentence):
sentence = "Hey fellow warriors"
sentence_array = sentence.split()
new_array = []
for word in sentence_array:
if len(word) >= 5:
word = word[::-1]
new_array.append(word)
else:
new_array.append(word)
print(new_array)
new_sentence = ' '.join(new_array)
print(new_sentence)
return new_sentence

python: conditional statement with else statement in loop

How would I be able to make this if statement more efficient?
if ',' in my_string:
my_string = my_string.split(',', 1)[0]
return ', '
elif '.' in my_string:
my_string = my_string.split('.', 1)[0]
return '. '
elif '?' in my_string:
my_string = my_string.split('?', 1)[0]
return '? '
elif '!' in my_string:
my_string = my_string.split('!', 1)[0]
return '! '
elif ';' in my_string:
my_string = my_string.split(';', 1)[0]
return '; '
else:
self.qstring = my_string
return None
I could make a list like:
my_list = [',', '.', '?', '!', ';']
and loop through, but I'm not sure how to still use the else statement if I put it all in a loop. Any thoughts?
Loop over the list you have:
for delim in my_list:
if delim in my_string:
my_string = my_string.split(delim, 1)[0]
return delim + ' '
self.qstring = my_string
return None
Because the loop will return the part after the loop is not executed if any delimiter matched.
Use re:
import re
(mystring, delim) = re.split(r'([,\.\?;] )', mystring, 1)[:2]
return delim
Remove all the assignments to my_string. Since this is a local variable, this achieves nothing because the value is never returned.

Categories

Resources