Capitalize only the first letter of sentences in python,using split function - python

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.

Related

Censoring the given word in a text

I am a beginner in Python. This is a challenge that I've found in a forum.
This program is censoring the words' (which has given by the user) letters with "*" except the first letter.
For example, If the sentence is "Every breath you take every move you make" and the input word is "every", the output should look like this:
2 incidents found.
Censored lyrics:
E**** breath you take e**** move you make
This was my only idea but it did not work.
text=input("Enter your text: ").lower()
word=input("Choose a word from the previously entered text: ").lower()
def censor(text,word):
t=text.split()
n=[]
for i in t:
if(i==word):
n.append("*"*len(word))
else:
n.append(i)
return " ".join(n)
print (censor)
Any help would be appreciated!
There are a few mistakes.
In Python 3 you have to use () while printing e.g. print("Hello world") NOT: print "Hello world"
i.lower()==word because "Every" != "every"
n.append(i[0]+"*"*(len(word)-1)) because you want first letter to stay
Code:
text=input("Enter your text: ").lower()
word=input("Choose a word from the previously entered text: ").lower()
def censor(text,word):
t=text.split()
n=[]
for i in t:
if(i.lower()==word):
n.append(i[0]+"*"*(len(word)-1))
else:
n.append(i)
return " ".join(n)
print(censor(text,word))
The issue here is that when you find the word, you just put * you never add the first letter. To fix that you would need:
n.append(word[0]+"*"*(len(word)-1))
instead of
n.append("*"*len(word))
Now it will add the first letter and the right number of * afterward.
It's not clear how it "doesn't work"; when I run your code this is the output:
***** breath you take ***** move you make
We can tweak your script to leave in the first letter:
if(i==word):
n.append(i[0] + "*"*(len(word)-1))
Giving the output as:
e**** breath you take e**** move you make
Again, it's not actually clear what wasn't working, but that's how you'd show the first letter of each censored word.
I have an approach related to Regex which could suit this purpose, just consider this as something you can expand on thinking to create your final program:
import re
blacklist = ['every']
def replace(match):
word = match.group()
if word.lower() in blacklist:
return word[0]+"*"*(len(word)-1)
else:
return word
text = 'Every breath you take every move you make'
text = re.sub(r'\b\w*\b', replace, text, flags=re.I|re.U)
print(text)
The advantage this has is that it will work with all kinds of word boundaries that regex recognizes.
You can check the output image below:

How to remove characters from string?

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)

Write a program that takes a user input string and outputs every second word

Please enter a sentence: The quick brown fox jumps over the lazy dog.
Output: The brown jumps the dog
I've been doing some learning in strings in python, but no matter what I do, I can't seem to write a program that will remove the 2nd letter of every sentence.
word=(input ("enter setence"))
del word[::2]
print(word[char],
end="")
Print("\n")
This was my closest attempt. At least I was able to write the sentence on the command prompt but was unable to get the required output.
string = 'The quick brown fox jumps over the lazy dog.'
even_words = string.split(' ')[::2]
You split the original string using spaces, then you take every other word from it with the [::2] splice.
Try something like :
" ".join(c for c in word.split(" ")[::2])
Try this:
sentenceInput=(input ("Please enter sentence: "))
# Function for deleting every 2nd word
def wordDelete(sentence):
# Splitting sentence into pieces by thinking they're seperated by space.
# Comma and other signs are kept.
sentenceList = sentence.split(" ")
# Checking if sentence contains more than 1 word seperated and only then remove the word
if len(sentenceList) > 1:
sentenceList.remove(sentenceList[1])
# If not raise the exception
else:
print("Entered sentence does not contain two words.")
raise Exception
# Re-joining sentence
droppedSentence = ' '.join(sentenceList)
# Returning the result
return droppedSentence
wordDelete(sentenceInput)
Try something like that.
sentence = input("enter sentence: ")
words = sentence.split(' ')
print(words[::2])

How to debug my Python code?

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

Converting a sentence to pig latin?

I'm trying to convert a sentence to pig latin but I can;t get it to work.
Conditions:
1. If it starts with a vowel, add way to the word (e.g eagle become eagleway)
2. If it starts with a consonant, check the second character and so on for as long as it's a consonant, keep checking and strip it out and put it at the end. (e.g grain becomes aingr)
Here is my code so far:
x = "The apple is extremely tasty. Great!"
y = x.split()
for i in y:
if(i[0] == "a" or i[0]=="e" or i[0]=="i" or i[0]=="o" or i[0]=="u"):
print(i+"way", end = " ")
I managed to do part 1. but I can't figure out part 2. I don't understand how to go through the chars and strip the whole part.
Any help is appreciated.
Thanks.
Firstly, pick better variable names:
sentence = "The apple is extremely tasty. Great!"
words = sentence.split()
for word in words:
Secondly, you can simplify your first check:
if word[0] in "aeiou":
print("{0}way".format(word), end=" ")
Finally, you could use while and slicing to move characters from the start of the word to the end:
else:
while word[0] not in "aeiou":
word = "".join((word[1:], word[0]))
print(word, end=" ")
Note that this still doesn't quite do what you want:
eTh appleway isway extremelyway asty.t eat!Gr
I will leave dealing with letter cases and punctuation as an exercise; I suggest making everything one case or the other and removing all punctuation before iterating through words.

Categories

Resources