How to get output in one line - python

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

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

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

return last word in a file that starts with capital letter

I'm trying to make a simple script that seraches for a designated .txt file for the last word that starts with a capital letter and returns it. If there are no words that start with a capital letter, it returns an empty string.
This is what I have tried so far:
def find_last_capitalised(file_name):
with open(file_name) as wordfile:
text_str = wordfile.read()
word_list = text_str.split()
upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for word in word_list:
if word.rfind(upper):
return word
else:
return " "
but this isn't working.
I also tried this:
with open(file_name) as wordfile:
text_str = wordfile.read()
word_list = text_str.split()
for word in word_list:
if word_list[-1].isupper():
return word_list[-1]
else:
return " "
Any help?
Others provided you with various method for doing your task. I want to explain why your 1st method do not work as intended:
upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if word.rfind(upper):
.rfind method of str is looking for position of last substring ABCDEFGHIJKLMNOPQRSTUVWXYZ inside word. I guess that your words do NOT contain such substring, in which case .rfind returns -1, which according to rules of Python evaluate to True (as it is not zero), so it would catch almost any word (it will give 0 or False only for words starting with ABCDEFGHIJKLMNOPQRSTUVWXYZ and containing only single ABCDEFGHIJKLMNOPQRSTUVWXYZ)
Fist of all, your algorithm would return the first capitlized word, not the last so there needs to be a little change in logic. Also the simplest way to check if word is capitalized is provided:
def find_last_capitalised(file_name):
with open(file_name) as wordfile:
text_str = wordfile.read()
word_list = text_str.split()
last_cap_word = " "
for word in word_list:
if word[0].isupper():
last_cap_word = word
return last_cap_word
Looks like you need reversed.
Ex:
def find_last_capitalised(file_name):
with open(file_name) as wordfile:
text_str = wordfile.read()
word_list = text_str.split()
for word in reversed(word_list): #reversed
if word[0].isupper():
return word
return " "
I did something like this.
import re
pattern = "[A-Z][a-zA-Z]+"
with open('input.txt', 'r') as file:
for el in reversed(file.readlines()):
res = re.findall(pattern, el)
if res:
print(res[-1])
def find_last_capitalised(word_list):
lastCapWord = " "
for word in word_list:
print(word)
if word[0].isupper():
lastCapWord = word
print('lastCapWord:', lastCapWord)
return lastCapWord
word_list = ['this', 'is', 'A', 'test']
find_last_capitalised(word_list)
Your algorithm is a little off. It doesn't go through each word in the list, instead it just returns based off the first word it sees. Assuming you make you make your word list into an array, the following code should work just fine.
You need are returning " " at first fail. That's why you don't get expected result.
def find_last_capitalised(file_name):
with open(file_name) as wordfile:
text_str = wordfile.read()
word_list = text_str.split()
for word in reversed(word_list):
if word[0].isupper():
return word
return ""
However if your file is much bigger, you might want to read file in a reverse order. Which will let you find what you looking for much easier.
import os
def find_last_capitalised(file_name):
with open(file_name) as wordfile:
wordfile.seek(0, os.SEEK_END)
position = wordfile.tell()
word = ''
while position >= 0:
qfile.seek(position)
next_char = qfile.read(1)
if next_char == " ":
if word[0].isupper():
return word
word = ''
else:
word += next_char
position -= 1
return ""
I suggest using similar approach to solve your problem.
You can try with reversed and is_upper keywords:
def find_last_capitalised(file_name):
with open(file_name) as wordfile:
text_str = wordfile.read()
word_list = text_str.split()
word_list = reversed(word_list)
for word in word_list:
if word[0].isupper():
return word
print(find_last_capitalised("demo.txt"))
def find_last_capitalised(file_name):
with open(file_name) as wordfile:
text_str = wordfile.read()
word_list = text_str.split(" ")
upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for word in reversed(word_list):
if upper.rfind(word[0]) >= 0:
return word
return " "
Please try with the above code ... If its not working let me know here.

Python, How do you check how many times an item appears in an array

I'm making a program that finds every word in a block of text and outputs each word and how many times the word was used.
My current code is here:
text = input("Please enter some text ")
terminator = len(text)
n = 0
word = ""
wordlist = []
while len(text) > 0:
if word != "":
wordlist.append(word)
text = text[n:]
word = ""
n = 0
for char in text:
if char != " ":
word = word + char
n = n + 1
else:
text = text[1:]
break
for item in wordlist:
print(item)
thanks :)
I'd do something like this:
import re
from collections import Counter
text = input("Please enter some text ")
text = re.sub(' +', ' ', text)
text = text.split(' ')
counter = Counter(text)
The line text = re.sub(' +', ' ', text) deals with cases where the user enters multiple consecutive spaces.

How to separate words that have uppercase and lowercase in Python?

I need to separate words that have at least one uppercase letter with the lowercase. I need to take input and separate uppercase words and lowercase words and print them both. Here is my code:
text = input("Input your text: ")
words0 = text.strip().split()
words1 = []
words2 = []
wordslen= len(words0)
for word in words0:
counter = 0
for x in word:
while counter != wordslen:
if x.isupper():
words1.append(word)
else:
words2.append(word)
counter += 1
wordsupper = list(set(words1))
wordslower = list(set(words2))
allwords = wordsupper + wordslower
for word in allwords:
print(word)
words = input("Input your text: ").strip().split()
lower, mixed = set(), set()
for word in words:
if word == word.lower():
lower.add(word)
else:
mixed.add(word)
print("Lowercase words: " + ", ".join(lower))
print("Mixed- and uppercase words: " + ", ".join(mixed))
which runs like:
Input your text: This is a Perl and Python party.
Lowercase words: a, and, is, party.
Mixed- and uppercase words: This, Python, Perl
To separate words that have only lowercase characters from the rest:
text = raw_input('Input text: ')
lower, rest = set(), set()
for word in text.split():
(lower if word == word.lower() else rest).add(word)
print(lower)
print(rest)
this is similar to previous posts, but uses map() instead of for word in words:
text = raw_input("Input your text: ")
words = text.strip().split()
upper = []
lower = []
def sort_word(word):
if word.lower() == word:
lower.append(word)
else:
upper.append(word)
map(sort_word, words)
Maybe something like this:
text = input("Input your text: ")
words = text.strip().split()
wordslower = []
wordsupper = []
for word in words:
# if the word is the same as word.lower() that means all the
# characters are lower case. Also, don't add duplicates to
# the list.
if word == word.lower():
if word not in wordslower:
wordslower.append(word)
else: # The word has at least one capital letter
if word not in wordsupper:
wordsupper.append(word)
print(wordslower)
print(wordsupper)
Try this:
def check(word):
for k in word:
if k != k.lower(): #If the letter is capitalized
return True
return False
text = input('Text: ')
text = text.strip().split()
wordsupper = []
wordslower = []
for k in text:
if check(k) == True:
wordsupper.append(k)
else:
wordslower.append(k)
print(wordslower)
print(wordsupper)

Categories

Resources