Get rid of spaces or join - python

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.

Related

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

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

How to censor multiple words in a sentence with hyphen

I have a function that replaces a single word in a sentence with a hyphen and It works fine what I was trying to add was for the user to enter multiple words separated by space and the function censors them. Is there any way to do this? My current code is attached below. Any help is appreciated. Thanks in advance.
def replaceWords(text, word):
word_list = text.split()
result = ''
hyphen = '-' * len(word)
count = 0
index = 0;
for i in word_list:
if i == word:
word_list[index] = hyphen
index += 1
result =' '.join(word_list)
return result
def main():
sentence = input(str("enter a sentence: "))
words = input(str("enter words to censor(separated by space): "))
print(replaceWords(sentence, words))
if __name__== '__main__':
main()
You already mostly have the right idea; just change word from being a single string to a list of strings, and use in to see if each word is part of that list.
>>> from typing import List
>>>
>>> def censor_words(text: str, bad_words: List[str]) -> str:
... return ' '.join(
... '-' * len(word) if word in bad_words else word
... for word in text.split()
... )
...
>>>
>>> print(censor_words("frankly my dear I don't give a damn", ['dear', 'give']))
frankly my ---- I don't ---- a damn
You can use string replace:
def replaceWords(text, words):
censored_words = words.split()
replace_character = "-"
for censor in censored_words:
text = text.replace(censor,replace_character*len(censor))
return text
def main():
sentence = input(str("enter a sentence: "))
words = input(str("enter words to censor(separated by space): "))
print(replaceWords(sentence, words))
if __name__== '__main__':
main()

How do I fix this code about index string?

I make a function to input string and return with head and tail with two indexes without space and punctuation. but it's return only "empty string"
def hello(word):
str_cnt = ""
for letter in word:
if letter not in string.whitespace and letter not in string.punctuation:
str_cnt += letter
if len(str_cnt) < 2 :
return "empty string"
else:
return str_cnt[:2] + str_cnt[-2:]
word = input("Input String : ")
result = hello(word)
print("Result: ",result)
I expect when I input "hello world!", and the actual output is "held"
or "Hi!" = "HiHi".
The problem is simply incorrect indentation:
import string
def hello(word):
str_cnt = ""
for letter in word:
if letter not in string.whitespace and letter not in string.punctuation:
str_cnt += letter
if len(str_cnt) < 2:
return "empty string"
return str_cnt[:2] + str_cnt[-2:]
word = input("Input String: ")
result = hello(word)
print("Result: ", result)
Indentation is everything in Python!
> python3 test.py
Input String: hello world!
Result: held
>
However, if the input is long, this is the wrong way to go about the problem. We test a lot of characters we'll never use against the whitespace and punctuation lists. Instead we should grab the first two valid characters from either end of the list and ignore the middle. Something like:
def hello(word):
unwanted = string.whitespace + string.punctuation
str_start = ""
for letter in word:
if letter not in unwanted:
str_start += letter
if len(str_start) == 2:
break
if len(str_start) < 2:
return "empty string"
str_end = ""
for idx in range(len(word) - 1, -1, -1):
if word[idx] not in unwanted:
str_end = word[idx] + str_end
if len(str_end) == 2:
break
return str_start + str_end
EXAMPLE
> python3 test2.py
Input String: telecommunications!
Result: tens
>
The letters 'lecommunicatio' were never tested as they had no effect on the eventual outcome.
You miss-indented the last if block:
import string
def hello(word):
str_cnt = ""
for letter in word:
if letter not in string.whitespace and letter not in string.punctuation:
str_cnt += letter
if len(str_cnt) < 2 :
return "empty string"
else:
return str_cnt[:2] + str_cnt[-2:]
word = input("Input String : ")
result = hello(word)
print("Result: ",result)
Example output:
Input String : Hello World!
Result: Held
Your issue is that you return after the first iteration through the work, no matter what.
Move the return nogic after the logic:
def hello(word):
str_cnt = ""
for letter in word:
if letter not in string.whitespace and letter not in string.punctuation:
str_cnt += letter
if len(str_cnt) < 2 :
return "empty string"
else:
return str_cnt[:2] + str_cnt[-2:]
The problem is indentation as everyone says, after correcting which it works. I would do it more pythonically as:
def hello(word):
w = ''.join([x for x in word if x not in string.whitespace and x not in string.punctuation])
return w[:2] + w[-2:] if len(w) > 1 else 'empty string'
Usage:
>>> hello('hello world!')
held

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(" ","")

Categories

Resources