how to remove special word from a string in function - python-3.x

Write a function fun(long string) with one string parameter that returns a string. The function should extract the words separated by a single space " ", exclude/drop empty words as well as words that are equal to "end" and "exit", convert the remaining words to upper case, join them with the joining token string ";" and return this newly joined string.
my code is......
def fun(long_string):
long_string = long_string.split(' ')
try:
if 'exit' in long_string:
long_string.remove('exit')
elif 'end' in long_string:
long_string.remove('end')
except ValueError:
pass
.....................
but it does not remove the "End or exit" .can someone pls help me to get it out. Im beginner in python and I stack here

You could try this and convert into the function as you wish - it's very straightforward.
Code did not fully test yet (but works for your inputs), so please try different inputs and you can learn to "improve" it to meet your requirement. Please ask if you have any questions.
inputs = "this is a long test exit string"
stop_words = ('end', 'exit')
outs = ''
for word in inputs.split():
if word in stop_words:
outs = inputs.replace(word, " ")
ans = ';'.join(w.upper() for w in outs.split()) # do the final conversion
Confirm it:
assert ans == "THIS;IS;A;LONG;TEST;STRING" # silent means True
Edit: add function:
def fun(long_string):
#s = "this is a long test exit string"
stop_words = ('end', 'exit')
outs = ''
for word in long_string.split():
if word in stop_words:
outs = long_string.replace(word, " ")
ans = ';'.join(w.upper() for w in outs.split())
return ans
text = "this is a long test exit string"
print(fun(text))

Related

Python: Insert space between every element in a list with one line description in for loop

I am trying to write a simple Encrype and Decrype system. I have a syntax question like the topic above, please take a look.
def en_num(pw):
en1 = [int(x) for x in pw]
for i in en1:
numstr = "".join(bin(int(i))[2:])
numstr += " "
return numstr
For example, input is "1 2", the output will be "1 10"
This can geve me the right output, however, I am trying to write this for loop in one line, like this
def en_num(pw):
en1 = [int(x) for x in pw]
numstr = "".join(bin(int(i))[2:] for i in en1)
return numstr
I don't know how to add the space between in this syntax, the result is "110"
Please take a look, thanks!
Try adding a space between the quotes on your join statement:
numstr = " ".join(bin(int(i))[2:] for i in en1)
That will separate each number.

In python 3 how can I return a variable to a function properly?

I am currently in school studying python and have a question. I am working on a midterm project that has to take an input, assign it to a list, if the first letter isnt capital - capitalize it..and count the number of words in the sentence.
While my code works.. I can't help but think I handled the arguments into the functions completely wrong. If you could take a look at it and help me out on how I could clean it up that would be excellent.
Please remember - I am new..so explain it like I am 5!
sentence_list = sentList()
sentence = listToString(sentence_list)
sentence = is_cap(sentence)
sentence = fix(sentence)
sentence = count_words(sentence)
def sentList():
sentence_list = []
sentence_list.append(input('Please enter a sentence: '))
return sentence_list
def listToString(sentence_list):
sentence = ""
sentence = ''.join(sentence_list)
return sentence
def is_cap(sentence):
sentence = sentence.capitalize()
return sentence
def fix(sentence):
sentence = sentence + "." if (not sentence.endswith('.')) and (not sentence.endswith('!')) and \
(not sentence.endswith('?')) else sentence
return sentence
def count_words(sentence):
count = len(sentence.split())
print('The number of words in the string are: '+ str(count))
print(sentence)
main()```
first of all, your code is very good as a beginner, good job dude.
so
to make your function run, you need call it after you defined them. but here you put the call at the top of the page.
the reason of that is python read the codes from top to bottom, so when he read the first that call a function that he didn't read 'til this line
the code should be like this:
def sentList():
sentence_list = []
sentence_list.append(input('Please enter a sentence: '))
return sentence_list
def listToString(sentence_list):
sentence = ""
sentence = ''.join(sentence_list)
return sentence
def is_cap(sentence):
sentence = sentence.capitalize()
return sentence
def fix(sentence):
sentence = sentence + "." if (not sentence.endswith('.')) and (not sentence.endswith('!')) and \ (not sentence.endswith('?')) else sentence
return sentence
def count_words(sentence):
count = len(sentence.split())
print('The number of words in the string are: '+ str(count))
print(sentence)
sentence_list = sentList()
sentence = listToString(sentence_list)
sentence = is_cap(sentence)
sentence = fix(sentence)
sentence = count_words(sentence)
I guess that it. if you have any another question. this community will always be here

Python string comparison function with input, while loop, and if/else statment

I'm trying to create a program that takes input from the user, -1 or 1 to play or quit, number of characters (n), two words for comparison (s1,s2), and calls this function: def strNcompare (s1,s2,n) and then prints the result. The function should return 0,-1,1 if n-character portion of s1 is equal to, less than, or greater than the corresponding n-character of s2, respectively. So for example is the first string is equal to the second string, it should return a 0.
The loop should end when the user enters, -1.
I'm just starting out in Python so the code I have is pretty rough. I know I need an if/else statement to print the results using the return value of the function and a while loop to make the program run.
This is what I have so far, it by no means works but my knowledge ends here. I don't know how to integrate the character (n) piece at all either.
com = input ("String comparison [1(play), -1(quit)]: ")
while (com=='1'):
s1 = input ("enter first string: ")
s2 = input ("enter second string: ")
n = int(input("number of characters: ")
s1 = s1[:n]
s1 = s2[:n]
if com==-1:
break
def strNcompare(s1,s2,n):
return s1==s2
elif s1==s2:
print(f'{s1} is equal to {s2}')
elif s1>s2:
print (f'{s1} is greater than {s2}')
elif s1<s2:
print (f'{s1} is less than {s2}')
else:
print ("QUIT")
break
com = input ("String comparison [1(play), -1(quit)]: ")
As of 10/05/2019 - I revised the code and now I am getting a syntax error at "s1 = s1[:n]"
it did not made much sense and especially the variable 'n' is not completely clear to me. I would not code it like that but I tried to be as close to your logic as possible.
com = input ("String comparison [1(play), -1(quit)]: ")
while (com=='1'):
s1 = input ("enter first string: ")
s2 = input ("enter second string: ")
n = input ("number of characters: ") #what is the purpose of this?
if s1==s2:
print(f'{s1} is equal than {s2}')
elif s1>s2:
print (f'{s1} is greater than {s2}')
elif s1<s2:
print (f'{s1} is less than {s2}')
else:
print ("Error")

How would I reverse each word individually rather than the whole string as a whole

I'm trying to reverse the words in a string individually so the words are still in order however just reversed such as "hi my name is" with output "ih ym eman si" however the whole string gets flipped
r = 0
def readReverse(): #creates the function
start = default_timer() #initiates a timer
r = len(n.split()) #n is the users input
if len(n) == 0:
return n
else:
return n[0] + readReverse(n[::-1])
duration = default_timer() - start
print(str(r) + " with a runtime of " + str(duration))
print(readReverse(n))
First split the string into words, punctuation and whitespace with a regular expression similar to this. Then you can use a generator expression to reverse each word individually and finally join them together with str.join.
import re
text = "Hello, I'm a string!"
split_text = re.findall(r"[\w']+|[^\w]", text)
reversed_text = ''.join(word[::-1] for word in split_text)
print(reversed_text)
Output:
olleH, m'I a gnirts!
If you want to ignore the punctuation you can omit the regular expression and just split the string:
text = "Hello, I'm a string!"
reversed_text = ' '.join(word[::-1] for word in text.split())
However, the commas, exclamation marks, etc. will then be a part of the words.
,olleH m'I a !gnirts
Here's the recursive version:
def read_reverse(text):
idx = text.find(' ') # Find index of next space character.
if idx == -1: # No more spaces left.
return text[::-1]
else: # Split off the first word and reverse it and recurse.
return text[:idx][::-1] + ' ' + read_reverse(text[idx+1:])

Print all words in a String without split() function

I want to print out all words in a string, line by line without using split() funcion in Python 3.
The phrase is a str(input) by the user, and it has to print all the words in the string, no matter it's size.Here's my code:
my_string = str(input("Phrase: "))
tam = len(my_string)
s = my_string
ch = " "
cont = 0
for i, letter in enumerate(s):
if letter == ch:
#print(i)
print(my_string[cont:i])
cont+=i+1
The output to this is:
Phrase: Hello there my friend
Hello
there
It is printing only two words in the string, and I need it to print all the words , line by line.
My apologies, if this isn't a homework question, but I will leave you to figure out the why.
a = "Hello there my friend"
b = "".join([[i, "\n"][i == " "] for i in a])
print(b)
Hello
there
my
friend
Some variants you can add to the process which you can't get easily with if-else syntax:
print(b.Title()) # b.lower() or b.upper()
Hello
There
My
Friend
def break_words(x):
x = x + " " #the extra space after x is nessesary for more than two word strings
strng = ""
for i in x: #iterate through the string
if i != " ": #if char is not a space
strng = strng+i #assign it to another string
else:
print(strng) #print that new string
strng = "" #reset new string
break_words("hell o world")
output:
hell
o
world

Resources