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.
Related
Typed code : How to combine the two parts in the code for 1 output >>
s= input()
def swap_case(s):
word = []
for char in s:
if char.islower():
word.append(char.upper())
else:
word.append(char.lower())
str1 = ''.join(word)
return str1
import re
new_string = re.sub('[^A-Za-z]+', '', s)
return new_string
print(swap_case(s))
You can first remove the characters that you want, and then do the swapping.
import re
s = input()
def swap_case(str):
word = []
for char in re.sub('[^A-Za-z]+', '', str):
if char.islower():
word.append(char.upper())
else:
word.append(char.lower())
return ''.join(word)
print(swap_case(s))
Or in short:
import re
s = input()
def swap_case(str):
return re.sub('[^A-Za-z]+', '', str).swapcase()
print(swap_case(s))
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
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.
I want to merge 2 continuous empty string in a list and make it into 1 empty string. For example if it finds 4 continuous empty string then it should make 2 empty string out of it. In Python.
str_list = ['hi',' ',' ','hello',' ',' ',' ',' ','bye']
Desired Output : ['hi',' ','hello',' ',' ','bye']
Hope it works:
count=0
l2=[]
for i in str_list:
if i==' ':
count+=1
if (count%2)==0:
l2.append(' ')
count=0
else:
l2.append(i)
you can use a while loop:
i = 0
new_list = []
while i < len(str_list) - 1:
if str_list[i] == str_list[i + 1] == ' ':
new_list.append(' ')
i += 2
else:
new_list.append(str_list[i])
i += 1
# grab the last character if last 2 are not ' '
if i < len(str_list):
new_list.append(str_list[i])
print(new_list)
output:
['hi', ' ', 'hello', ' ', ' ', 'bye']
Try this
count = 0
new_list = []
for i in str_list:
if i == ' ' and count == 0:
count = count + 1
elif i == ' ' and count % 2 == 0:
for j in range(count // 2):
new_list.append(' ')
else:
new_list.append(i)
count = 0
If you don't want to remove all single space:
words = ["hi", " ", " ", "hello", " ", " ", " ", " ", "bye", " "]
rv = []
d = " "
skip = True
for i in words:
if i == d:
skip = not skip
if skip:
continue
rv.append(i)
print(rv)
Output:
['hi', ' ', 'hello', ' ', ' ', 'bye', ' ']
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