How to output a sentence or phrase with no whitespace? - python

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

Related

How do we combine two activities - say one, remove numbers, special characters and two, convert uppercase to lowercase letters, and back

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

How to get output in one line

I do reverse string and input is The quick brow fox
def reverse_word(word):
for i in word:
re = (i[::-1])
print('Reversed words ==> '+ re )
def main():
word = input('Enter a line : ').split()
reverse_word(word)
main()
but my result is
Reversed words ==> ehT
Reversed words ==> kciuq
Reversed words ==> worb
Reversed words ==> xof
I want result like:
Reversed words ==> ehT kciuq worb xof
you can use end in print method
def reverse_word(word):
print('Reversed words ==> ', end='')
for i in word:
re = (i[::-1])
print(re, end=' ' )
def main():
word = input('Enter a line : ').split()
reverse_word(word)
main()
Can try this one :
def reverse_word(word):
print("Reversed words ==>", end="")
for i in word:
re = (i[::-1])
print(" " + re, end="")
def main():
word = input('Enter a line : ').split()
reverse_word(word)
main()
In order to get a single line output , you can have a global string out = "" To which you will concatenate your resulting words.
out += " " + re
Inside the for loop
And this can be printed right after the end of the loop.
out = ""
def reverse_word(word):
for i in word:
re = (i[::-1])
out += " " + re
print("Reversed Words ==> " + out)
def main():
word = input('Enter a line : ').split()
reverse_word(word)
main()
def reverse_word(word):
res = ""
for i in word:
re = (i[::-1])
res += " "+re
return 'Reversed words ==>'+ res
word = input('Enter a line : ').split()
print(reverse_word(word))
Believe this would have desired effect.
Not really a question asked so no need to explain it further. Keep it simple!
When you say word it looks like this is really a collection of words, so words is probably a better name, and each of those should probably be word rather than i.
def reverse_words(words):
for word in words:
re = (word[::-1])
print('Reversed words ==> '+ re )
def main():
words = input('Enter a line : ').split()
reverse_words(words)
main()
Now, we can use a generator expression to generate the reversed word for each word.
(word[::-1] for word in words)
And let's join those with a space.
' '.join(word[::-1] for word in words)
And putting it into a function, using an f-string to print it:
def reverse_words(words):
print(f"Reversed words ==> {' '.join(word[::-1] for word in words)}")
Alternatively, we can use reversed.
def reverse_words(words):
print(f"Reversed words ==> {' '.join(''.join(reversed(word)) for word in words)}")

Accounting spaces in palindrome program

This is a program that accepts a string of words and checks if the words are palindromes and if it is one, it prints it. However if a string has a space in it, my program won't count it as a palindrome (Example: nurses run). What should I be adding to make the program exclude the space, when it's accounting for palindromes?
Palindrome: a word, phrase, or sequence that reads the same backwards as forwards, e.g. 'madam' or 'nurses run'
import sys
strings = []
for s in sys.argv[1:]:
strings += [s]
def is_palindrome(word):
if len(word) <= 2 and word[0] == word[-1]:
return True
elif word[0] == word[-1]:
is_palindrome(word[1:-1])
return True
else:
return False
def printpalindromes(strings):
for s in strings:
if is_palindrome(s) == True:
print(s)
printpalindromes(strings)
Try stripping out the whitespaces before doing the palindrome check
>>> x = "nurses run"
>>> x.replace(" ", "")
'nursesrun'
You can use reversed:
def palindrome(word):
if ' ' in word:
word = word.replace(' ', '')
palindrome = reversed(word)
for letter, rev_letter in zip(word, palindrome):
if letter != rev_letter:
return 'Not Palindrome'
return 'Palindrome'
Your code is still incorrect in the elif statement. You've added return True when you should actually be returning the response from your recursive call as previously mentioned.
def is_palindrome(word):
if len(word) <= 2 and word[0] == word[-1]:
return True
elif word[0] == word[-1]:
return is_palindrome(word[1:-1])
else:
return False
Here's a simpler solution of your problem:
import sys
sys.argv = [" nurses ", " run "]
word = "".join([s.strip() for s in sys.argv])
print("{} {} palindrome".format(word, "is" if word == word[::-1] else "is not"))
or you can just create the word out of sys.argv like this:
word = "".join(sys.argv).replace(" ","")

Get rid of spaces or join

I tried to read this as a palindrome, backward, it works within one word with no spaces but doesn't with Taco Cat.
How do I join or get rid of spaces?
def is_palindrome():
string = input("Enter a palindrome: ")
string = string.lower()
string = string.whitespace()
rev_str = reversed(string)
if list(string) == list(rev_str):
print("True")
else:
print("False")
is_palindrome()
string = string.replace(' ', '') can works fine here:
def is_palindrome():
string = str(input("Enter a palindrome: "))
string = string.lower()
string = string.replace(' ', '')
rev_str = reversed(string)
if list(string) == list(rev_str):
print("True")
else:
print("False")
is_palindrome()
Demo:
[user#localhost ~]$ python test.py
Enter a palindrome: Taco Cat
True
[user#localhost ~]$
You also can try put a print(string) after string = string.replace(' ', '') and see what's the output. However I got tacocat.

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