Reputation: 19
Basically as the title says, I want the sentences of the user input to be capitalized, but not lose their capitalization in the process. The input's supposed to be two sentences that get separated by periods. The code I have here outputs them the sentences, but not joined or keeping the rest of the capitalization.
def main():
user_input = input("Enter the sentence you would like to be modified!: ").split(". ")
capitalized_sentences = [user_input[0].upper() + user_input[1:] for sentence in user_input]
recombined_sentences = ". ".join(capitalized_sentences)
Upvotes: 1
Views: 1686
Reputation: 56
Just edit the first character of each split to be upper:
# For this example, lets use this string. However, you would still use
# user_input = input("...") in your actual code
user_input = "for bar. egg spam."
# Turn the user_input into sentences.
# Note, this is assuming the user only is using one space.
# This gives us ["foo bar", "egg spam"]
sentences = user_input.split(". ")
# This is called a list comprehension. It's a way of writing
# a for-loop in Python. There's tons of documentation on it
# if you Google it.
#
# In this loop, the loop variable is "sentence". Please be mindful
# that it is a singular form of the word sentences.
#
# sentence[0].upper() will make the first letter in sentence uppercase
# sentence[1:] is the remaining letters, unmodified
#
# For the first iteration, this becomes:
# "f".upper() + "oo bar"
# "F" + "oo bar"
# "Foo bar"
capitalized_sentences = [sentence[0].upper() + sentence[1:]
for sentence
in sentences]
# At this point we have ["Foo bar", "Egg spam"]
# We need to join them together. Just use the same ". " we
# used to split them in the beginning!
#
# This gives us "Foo bar. Egg spam."
recombined_sentences = ". ".join(capitalized_sentences)
Replace "sentences" with your user_input
bit
Note, there might be a "gotcha" if the user inputs sentences of a format you aren't expecting. For example, what if the user entered two spaces instead of one? Then the above code would try to capitalize a whitespace character. You would need to account for that.
Upvotes: 2
Reputation: 145
It's very simple: You can use the String method upper() on a part of the string.
Here is a one-liner to do just that:
CapWord = "".join([c.upper() if i == 0 else c for i, c in enumerate([j for j in rawWord])])
Just replace CapWord and rawWord with respective values (you can change them to sentences / words depending on what you want to do.
What it does:
Upvotes: -1