wondering how to write the python code for sentence capitalizer [duplicate] - python

This question already has answers here:
How to concatenate (join) items in a list to a single string
(11 answers)
Closed 2 years ago.
I am currently doing a task but I am stuck at the moment, so here is the code so far I have written:
string = input('please enter a string: ')
s = []
def sentenceCapitalize(string):
strn = string.split('. ') #convert to a list
for x in strn:
y = x[0].upper()
y += x[1:].lower()
s.append(y)
print('.'.join(s))
sentenceCapitalize(string)
It only gets me the result as a list and period is disappeared
Unexpected Output:
Expected Output:
Hello. My name is Joe. What is your name?
And here is the question from the book:
Write a program with a function that accepts a string as an argument
and returns a copy of the string with the first character of each
sentence capitalized. For instance, if the argument is “hello. my name
is Joe. what is your name?” the function should return the string
“Hello. My name is Joe. What is your name?” The program should let the
user enter a string and then pass it to the function. The modified
string should be displayed.
Can you fix this solution? thanks.

The main three errors you have in your code are:
You convert to lower case the rest of the sentence, so for example Joe will become joe
You split based on ('. '), but when concatenating back you join by ('.'), so you are missing the white space
You need a regex split, to consider both , and .. In the regex you pass the two options separated by |, and for the case of dot you need to add before '' since '.' itself is an operator in regex. More about Regular Expression
Try this:
string = input('please enter a string: ')
s = []
import re
def sentenceCapitalize(string):
strn = re.split(',|\.', string) #convert to a list
for x in strn:
y = x[0].upper()
y += x[1:]
s.append(y)
print('.'.join(s))
sentenceCapitalize(string)

One sentence solution:
print('. '.join([st[0].upper() + st[1:] for st in string.split('. ')]))

Related

Having problem in this very basic PYTHON program [duplicate]

This question already has answers here:
Efficient way to add spaces between characters in a string
(5 answers)
Closed 1 year ago.
So i am making a very simple python program which takes a string as input from user and adds a '-' between every character but the problem is it adds it to last one too but i don't want that...
Here's the code:
string = input("Enter the string to be traversed: ")
for ch in string:
print(ch , end = "-")
Output:
Enter the string to be traversed: helloworld
h-e-l-l-o-w-o-r-l-d-
I don't want it to print '-' after the last character...
This is a common problem and there is a string method to deal with it. Instead of a for loop, join the characters with a dash.
string = input("Enter the string to be traversed: ")
print("-".join(string))
.join will work with anything that iterates strings. In your case, a string does that, character by character. But a list or tuple would work as well.

Python: How to interpret user input as a list (beginner) [duplicate]

This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 4 months ago.
I am trying to write a function that takes a user inputted list, and transforms it into a string that separates each value inside the list with a comma, and the last value in the list with "and". For example, the list ['cats', 'dogs', 'rabbits', 'bats'] would be transformed to: 'cats, dogs, rabbits, and bats'.
My code works if I assign a list to a variable and then pass the variable to my newString function, but if I pass a user input to my function, it will treat every character in the user input as a separate list value.
So my question is, how can I tell Python that I want input() to be read as a list. Is this even possible? I am very new to Python and programming in general, so Lists and Tuples is about as far as I know so far. I am learning dictionaries now. My code is printed below, thanks.
def listToString(aList):
newString = ''
for i in range(len(aList) - 1):
newString += aList[i] + ', '
newString = newString + 'and ' + aList[-1]
return(newString)
spam = list(input())
print(listToString(spam))
input() always gives you just a string.
You can analyze that string depending on how the user is supposed to enter the list.
For example, the user can enter it space separated like 'cats dogs rabbits bats'. Then you do
input_list = input().split()
print(listToString(input_list))
You can also split on , or any delimiter you like.
If you want to read a list literal from user input, use ast.literal_eval to parse it:
import ast
input_list = ast.literal_eval(input()) # or ast.literal_eval(raw_input()) on Python 2
You could build a list from the input and use your current working code to format it as you want.
def get_user_input():
my_list = []
print('Please input one word for line, leave an empty line to finish.')
while True:
word = input().strip()
if word:
my_list.append(word)
else:
break
return my_list

Remove letters from a given string

So my homework assignment is to remove initials of a given name, from a given string, using user inputs to define the variables. As I run the script below, it only registers one name.
def removeChar(initials, string):
initials = initials
string = string
for char in initials:
modified = string.replace(char, "")
print modified
return modified
def getInitials(name, string):
initials = ""
for i in name.lower().split():
initials += i[0]
print initials
removeChar(initials, string)
def main():
name = raw_input("What is your name? \n")
string = raw_input("What string would you like to remove your initials from? \n")
getInitials(name, string)
This is the output:
What is your name?
John Doe
What string would you like to remove your initials from?
Arjajbian Ndigdhts
Arjajbian Nights
Why wouldn't it remove the first initial?
Your problem lies here:
modified = string.replace(char, "")
You are always using replace on the original string, so it removes each individual character from the original string and returns a new one. Just use string = string.replace(char, "")
Or else your function will always return a string that is the original string with the last initial removed.
you dont need the
initials = initials
string = string
as this does nothing your telling to make this variable the same as it is already
Also
I think it is this
modified = string.replace(char, "")
you make this create a variable called modified but later on in the code you are saying to get String and not modified
either change String to modified apart from in the top def or change the modified to string and then it will work hopefully
While #juanpa.arrivillaga has pointed out your problem, there is a much more Pythonic way to remove the characters j and d from your input string; Using a generator expression:
>>> input_str = "Arjajbian Ndigdhts"
>>> ''.join(c for c in input_str if c.lower() not in 'jd')
'Arabian Nights'
>>>
This works by iterating through input_str and only passing the characters to ''.join() which are not j or d.

Print multiple occurrences in a string [duplicate]

This question already has answers here:
Python Regex to find a string in double quotes within a string
(6 answers)
Closed 6 years ago.
I'm trying to write a function where the input has a keyword that occurs multiple times in a string and will print the stuff that has double quotation marks between them after the keyword. Essentially...
Input= 'alkfjjiekeyword "someonehelpmepls"fjioee... omgsos someonerandom help helpppmeeeeeee keyword"itonlygivesmeoneinsteadofmultiple"... sadnesssadness!sadness'
Output= someonehelpmepls
itonlygivesmeoneinsteadofmultiple
If its possible to have the outputs as its own line that would be better.
Here's what I have so far:
def getEm(s):
h = s.find('keyword')
if h == -1
return -1
else:
begin = s.find('"',h)
end = s.find('"', begin+1)
result = s[begin +1:end]
print (result)
Please don't suggest import. I do not know how to do that nor know what it is, I am a beginner.
Let's take some sample input:
>>> Input= 'alkfjjiekeyword "someonehelpmepls"fjioee... omgsos someonerandom help helpppmeeeeeee keyword"itonlygivesmeoneinsteadofmultiple"... sadnesssadness!sadness'
I believe that one " was missing from the sample input, so I added it.
As I understand it, you want to get the strings in double-quotes that follow the word keyword. If that is the case, then:
def get_quoted_after_keyword(input):
results = []
split_by_keyword = input.split('keyword')
# you said no results before the keyword
for s in split_by_keyword[1:]:
split_by_quote = s.split('"')
if len(split_by_quote) > 1:
# assuming you want exactly one quoted result per keyword
results.append(split_by_quote[1])
return results
>print('\n'.join(get_quoted_after_keyword(Input))
>someonehelpmepls
>itonlygivesmeoneinsteadofmultiple
How it works
Let's look at the first piece:
>>> Input.split('keyword')
['alkfjjie',
' "someonehelpmepls"fjioee... omgsos someonerandom help helpppmeeeeeee ',
'"itonlygivesmeoneinsteadofmultiple"... sadnesssadness!sadness']
By splitting Input on keyword, we get, in this case, three strings. The second string to the last are all strings that follow the word keyword. To get those strings without the first string, we use subscripting:
>>> Input.split('keyword')[1:]
[' "someonehelpmepls"fjioee... omgsos someonerandom help helpppmeeeeeee ',
'"itonlygivesmeoneinsteadofmultiple"... sadnesssadness!sadness']
Now, our next task is to get the part of these strings that is in double-quotes. To do that, we split each of these strings on ". The second string, the one numbered 1, will be the string in double quotes. As a simpler example, let's take these strings:
>>> [s.split('"')[1] for s in ('"one"otherstuff', ' "two"morestuff')]
['one', 'two']
Next, we put these two steps together:
>>> [s.split('"')[1] for s in Input.split('keyword')[1:]]
['someonehelpmepls', 'itonlygivesmeoneinsteadofmultiple']
We now have the strings that we want. The last step is to print them out nicely, one per line:
>>> print('\n'.join(s.split('"')[1] for s in Input.split('keyword')[1:]))
someonehelpmepls
itonlygivesmeoneinsteadofmultiple
Limitation: this approach assumes that keyword never appears inside the double-quoted strings.

validation from input if character is alphabetical [duplicate]

This question already has answers here:
How to gather information from user input and apply it elsewhere
(3 answers)
Closed 6 years ago.
Hi I am new to programming and I am trying to write a code that will gather information from the input and determine if it is a valid alphabet.
I previously asked this question before but the answers given just didn't work so I am asking the question again. Please help
words = []
word = input('Character: ')
while word:
if word not in words:
words.append(word)
word = input('Character: ')
print(''.join(words),'is a a valid alphabetical string.')
suppose I choose three letters then the output of my code then pressed enter
on the fourth,
the code will be:
Character:a
Character:b
Character:c
Character:
abc is a valid alphabetical string.
I want to add to this code so that when I type in a character that is not
from the alphabet the code will do something like this.
Character:a
Character:b
Character:c
Character:4
4 is not in the alphabet.
This is exactly how I want my output to be.
If you look at the string class I think you will find it has some variables you would find useful.
from string import letters
word = raw_input("Character: ")
words = []
while word and word in letters:
if word not in words:
words.append(word)
word = raw_input('Character: ')
I don't have python on this computer but I think that you will find this chunk of code works. Also, the string class has a several other variables you might find useful including digits, punctuation, printable etc
You may use string.isalpha() function to find whether the input is alphabetic or not.
>>> 'a'.isalpha()
True <-- as 'a' is alphabet
>>> 'A'.isalpha()
True <-- as 'A' is also alphabet
>>> ''.isalpha()
False <-- empty string
>>> '1'.isalpha()
False <-- number
-------------------------
>>> 'ab'.isalpha()
True <-- False, since 'ab' is alphabetic string
# NOTE: If you want to restrict user to enter only one char at time,
# you may add additional condition to check len(my_input) == 1
>>> len('ab') == 1 and 'ab'.isalpha()
False
In order to get the input from user, you can do:
Using raw_input:
x = raw_input() # Value of x will always be string
Using input
x = input() # Value depends on the type of value
x = str(x) if x else None # Convert to str type. In case of enter with value set as None

Categories