The purpose of my code it to intake a string from a user and turn into a non case-sensitive list. Then I need to intake a second string from the user then output the position of the second given string. This is my code:
UserSentence = input('Enter your chosen sentence: ') #this is where the user inputs their sentence
from string import punctuation #this 'fetches' the punctuation from the string
tbl=str.maketrans({ord(ch):" " for ch in punctuation})
UserSentence = UserSentence.lower().translate(tbl).split()#.split() turns the input sentence into a list,...
#...this will help to identify where a word appears...
#...in the sentence. The .lower() also turns the...
#...string into lowercase so it is not case sensitive.
UserWord = input('Enter a word from the sentence: ')#this is where the user inputs their word from the sentence
UserWord = UserWord.lower()#.lower() is used to make UserWord not case sensitive
for i in range(len(UserSentence)):
if UserSentence (i) == UserWord:
print ('Your chosen word appears in: ')
To index a sequence you need to use []
if UserSentence[i] == UserWord:
If you are trying to find which index (by word) their word is you can do
if UserWord in UserSentence:
print('Your word is located at {}'.format(UserSentence.index(UserWord)))
Or similarly
try:
print('Your word is located at {}'.format(UserSentence.index(UserWord)))
except ValueError:
print('Your word is not in the sentence')
Couple of errors here:
If you're using Python 2, use raw_input for strings. In Python 3 input is okay.
Your maketrans call is weird
For looking up if a word is inside a list you don't any loops or own comparisons. Python can do that for you.
Please stick to PEP0008. It tells you how you should format your code so that it's easier to read.
Your rewritten and tested code:
from string import punctuation, maketrans
user_sentence = raw_input('Enter a sentence: ')
trans = maketrans("", "")
user_sentence = user_sentence.lower().translate(trans, punctuation).split()
user_word = raw_input('Enter a word from the sentence: ')
user_word = user_word.lower()
if user_word in user_sentence:
print ('Your chosen word appears in the sentence.')
Related
I'm working on my Python homework of: Write a program that requests a sentence, a word in the sentence, and another word and then displays the sentence with the first word replaced by the second.
The hint says to use the method "find" to help solve it but i can't think of a way to do so.
sentence = input("Enter a sentence.")
word = input("Enter word to replace. ")
replacement = input("Enter replacement word. ")
A = sentence.find(word)
print(sentencereplacement)
I'm not sure how to use find and what to print in the end.
Normally you can use replace method but if your teacher says so.
We will just find where the word starts at the sentence and we will cut this word and place our new one.
sentence = input("Enter a sentence.")
word = input("Enter word to replace. ")
replacement = input("Enter replacement word. ")
start = sentence.find(word)
end = start + len(word)
print(sentence[0:start] + replacement + sentence[end : len(sentence)])
It is literally called .replace()
result = sentence.replace(word, replacement)
I have a program where I need to prompt the user for an input of a word and a key. Next, the program should remove all the spaces, punctuation and all numbers from the word and convert all the letters into uppercase. Once that is done I need the program to replace all the characters of the word with the key. So if the word is a library, and the key is moose, the program should print out moosemo. I know that this part includes something like append.key(len plaintext) something of this fashion, but I'm not exactly sure how. I don't have a lot of the code done because I am pretty lost. Here is what I have so far:
phrase = input("Please enter the phrase to be encrypted: ") #prompt user for phrase
encryptionkey = input("Please enter the key: ") #prompt user for encryption key
print(phrase.upper()) #converts all characters from phrase to uppercase
If anyone knows what to do or what to change, please let me know. Please show the change in code with your response. Thanks in advance
I used answers from here and here to make compose this.
Here is one way you might do it, using the string class to get rid of punctuation and numbers.
import string
phrase = input("Please enter the phrase to be encrypted: ") #prompt user for phrase
encryptionkey = input("Please enter the key: ") #prompt user for encryption key
#replace - gets rid of spaces
#first translate - gets rid of punctuation
#second translate - gets rid of digits
#upper - capitalizes.
phrase = phrase.replace(" ", "")\
.translate(str.maketrans('', '', string.punctuation))\
.translate(str.maketrans('','',string.digits))\
.upper()
times_to_repeat = len(phrase)//len(encryptionkey)
leftover_length = len(phrase)%len(encryptionkey)
#multiply string by how many times longer it is than the encryption, then add remaining length.
#in python you can do 'string'*2 to get 'stringstring'
final_phrase = encryptionkey*times_to_repeat+encryptionkey[:leftover_length]
print(final_phrase)
Output:
# Only keep the alphabet characters
phrase = ''.join(c for c in phrase if c.isalpha())
# Add the encryption key at least 1 more times than divisible (to count for remainder)
# and slice the output to the length needed
phrase = (encryptionkey * (1 + len(phrase) // len(encryptionkey)) [:len(phrase)]
How to remove user defined letters from a user defined sentence in Python?
Hi, if anyone is willing to take the time to try and help me out with some python code.
I am currently doing a software engineering bootcamp which the current requirement is that I create a program where a user inputs a sentence and then a user will input the letters he/she wishes to remove from the sentence.
I have searched online and there are tons of articles and threads about removing letters from strings but I cannot find one article or thread about how to remove user defined letters from a user defined string.
import re
sentence = input("Please enter a sentence: ")
letters = input("Please enter the letters you wish to remove: ")
sentence1 = re.sub(letters, '', sentence)
print(sentence1)
The expected result should remove multiple letters from a user defined string, yet this will remove a letter if you only input 1 letter. If you input multiple letters it will just print the original sentence. Any help or guidance would be much appreciated.
If I understood correctly we can use str.maketrans and str.translate methods here like
from itertools import repeat
sentence1 = sentence.translate(str.maketrans(dict(zip(letters, repeat(None)))))
What this does line by line:
create mapping of letters to None which will be interpreted as "remove this character"
translation_mapping = dict(zip(letters, repeat(None))
create translation table from it
translation_table = str.maketrans(translation_mapping)
use translation table for given str
sentence1 = sentence.translate(translation_table)
Test
>>> sentence = 'Some Text'
>>> letters = 'te'
>>> sentence.translate(str.maketrans(dict(zip(letters, repeat(None)))))
'Som Tx'
Comparison
from timeit import timeit
print('this solution:',
timeit('sentence.translate(str.maketrans(dict(zip(letters, repeat(None)))))',
'from itertools import repeat\n'
'sentence = "Hello World" * 100\n'
'letters = "el"'))
print('#FailSafe solution using `re` module:',
timeit('re.sub(str([letters]), "", sentence)',
'import re\n'
'sentence = "Hello World" * 100\n'
'letters = "el"'))
print('#raratiru solution using `str.join` method:',
timeit('"".join([x for x in sentence if x not in letters])',
'sentence = "Hello World" * 100\n'
'letters = "el"'))
gives on my PC
this solution: 3.620041800000024
#FailSafe solution using `re` module: 66.5485033
#raratiru solution using `str.join` method: 70.18480099999988
so we probably should think twice before using regular expressions everywhere and str.join'ing one-character strings.
>>> sentence1 = re.sub(str([letters]), '', sentence)
Preferably with letters entered in the form letters = 'abcd'. No spaces or punctuation marks if necessary.
.
Edit:
These are actually better:
>>> re.sub('['+letters+']', '', sentence)
>>> re.sub('['+str(letters)+']', '', sentence)
The first also removes \' if it appears in the string, although it is the prettier solution
You can use a list comprehension:
result = ''.join([x for x in sentence if x not in letters])
Your code doesn't work as expected because the regex you provide only matches the exact combination of letters you give it. What you want is to match either one of the letters, which can be achieved by putting them in brackets, for example:
import re
sentence = input("Please enter a sentence: ")
letters = input("Please enter the letters you wish to remove: ")
regex_str = '[' + letters + ']'
sentence1 = re.sub(regex_str, '', sentence)
print(sentence1)
For more regex help I would suggest visiting https://regex101.com/
user_word = input("What is your prefered sentence? ")
user_letter_to_remove = input("which letters would you like to delete? ")
#list of letter to remove
letters =str(user_letter_to_remove)
for i in letters:
user_word = user_word.replace(i,"")
print(user_word)
How can I capitalize the first letter of a input sentence in python?
Output has to be: Enter sentence to be capitalized:+ input sentence
input_string =input("Enter sentence to be capitalized: ")
def capitalize_first(input_string):
output=input_string.split('.')
i=0
while i<len(output)-1:
result=output[i][0].upper()+output[i][1:]+"."
print("Enter sentence to be capitalized:"+result)
How about input_string.title()?
input_string =input("Enter sentence to be capitalized: ")
def capitalize_first(input_string):
result = input_string.title()
print("Enter sentence to be capitalized:"+result)
This built-in method only capitalises the first character and keeps other ones lower, just like how titles work.
As you can see, the extra capitals in THIS IS AN AMAZING are changed.
>>> input_string = "Hello World THIS IS AN AMAZING day!!!"
>>> input_string.title()
>>> 'Hello World This Is An Amazing Day!!!'
In my opinion there are many ways to do so, but title() is the easiest. You can use upper() inside a for loop which iterating the input string, or even capitalize(). If the goal is to capitalise only the first letter of every word. Then you can't use above methods since they capitalise the word in traditional way (first letter is capitalise and others in simple letters regardless what user entered). To avoid that and keep any capitalise letters inside a word as it is, just like user entered.
Then this might be a solution
inputString=input("Your statement enter value or whatever")
seperatedString=inputString.split()
for i in seperatedString:
i[0].upper()
print("Anything you want to say" + i)
sentence="test Sentence"
print(sentence.title()) #makes the first letter of every word in sentence capital
print(sentence[0].upper()+sentence[1:] ) #retains case of other charecters
print(sentence.capitalize()) #makes all other charecters lowercase
Output:
Test Sentence
Test Sentence
Test sentence
Answer your specific question
def modify_string(str1):
sentence_list=str1.split('.')
modify_this=input("Enter sentence to be modified: ")
for idx, item in enumerate(sentence_list):
modify_this_copy=modify_this
if item.lower().strip()==modify_this.lower().strip():
sentence_list[idx]=modify_this_copy[0].upper()+modify_this_copy[1:]
return '. '.join(sentence_list)
string1="hello. Nice to meet you. hello. Howdy."
print(modify_string(string1))
Output
Enter sentence to be modified: hello
Hello. Nice to meet you. Hello. Howdy.
# Reading line of text
text = input("Enter text: ")
print("English: " ,text)
# Removing punctuation
text = removePunctuation(text)
# Converting to lower case
text = text.lower()
# Iterating over words
for word in text.split(" "):
# Converting word to Pig Latin form
word = pigLatin(word)
# Printing word
print(word, end = " ");
How can I get it to say Pig: and then the Pig Latin form? Every time i try this, it just adds the Pig Latin transformation to the previous word.
You're trying to make one variable do two things at once.
If you want to use the old value later (in your print) then quit destroying the original value:
pl_word = pigLatin(word)
print (word, pl_word)
print("Pig:", word)
Next time, please use capital letters and some markdown... https://stackoverflow.com/editing-help