Reputation: 57
sentence = "The quick brown fox jumps over the lazy dog."
for word in sentence:
if word.startswith("f" or "F"):
uppercase_text = sentence.replace(word, str(word.upper()))
print(uppercase_text)
if word.endswith("e" or "E"):
e_text = sentence.replace(word, str("my"))
print(e_text)
My program is supposed to replace every word in the string that ends with the letter "e" with the word "my." I am also trying to convert every word that ends with the letter "f" into uppercase. However, only the first letter is being capitalized instead of the entire word. And every letter "e" is getting replaced with "my" and still leaves the rest of the word intact, instead of replacing the whole word with the word "my."
Thmy quick brown fox jumps ovmyr thmy lazy dog.
The quick brown Fox jumps over the lazy dog.
Thmy quick brown fox jumps ovmyr thmy lazy dog.
Thmy quick brown fox jumps ovmyr thmy lazy dog.
My output looks like this. My desired output would look like "My quick brown FOX jumps over my lazy dog," and this new string would only print once. I'm not sure why the whole word is not getting replaced / capitalized.
I also wasn't sure how to combine the code for uppercase_text and e_text so the sentence only prints once. I'm aware it's printing twice right now because those are two separate variables. Not sure why it's getting printed four times though, and I don't know how to fix that either.
I've tried making variables for the text that is supposed to be manipulated, like this:
ends_with_e = sentence.endswith("e" or "E")
for ends_with_e in sentence:
e_text = sentence.replace(word, str("my"))
print(e_text)
But this prints even more nonsensical output:
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
The quick brown fox jumps over the lazy dogmy
I can see what's going on here - the program is just printing "my" at the end of the string, but I can't tell how to fix this either.
Thanks to anyone who has any insight on this!
Upvotes: 1
Views: 797
Reputation: 3161
Your code will parse the string by character, not by word.
sentence = "The quick brown fox jumps over the lazy dog."
for word in sentence: # By character, not word
...
Use .split()
to create an array delimited by whitespace.
https://www.w3schools.com/python/ref_string_split.asp
sentence = "The quick brown fox jumps over the lazy dog."
for word in sentence.split(): # Creates an array of words
...
In your logic you are calling sentence.replace(...)
which means you're looking through the entire input sentence but since you're using a loop, you should only handle each word at a time.
Use instead:
sentence = "The quick brown fox jumps over the lazy dog."
result = [] # Create result array since the `sentence` array is immutable
for word in sentence.split():
word_result = word
if word.startswith("f" or "F"):
word_result = word.upper()
if word.endswith("e" or "E"):
word_result = "my"
result.append(word_result)
print(" ".join(result)) # Print once with space reinserted
You are also printing for each "pass" of the sentence
so that's why you have multiple lines. Print only once at the end.
This doesn't handle if both cases are met like words such as "fire".
Upvotes: 0
Reputation: 323
Getting words from a sentence requires a process called tokenization. The .split()
method tokenizes by spaces. Another popular way of tokenization is through NLTK:
>>> from nltk.tokenize import word_tokenize
>>> s = "The quick brown fox jumps over the lazy dog."
>>> word_tokenize(s)
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog', '.']
Note that the NLTK's tokenizer detects the punctuation at the end of the sentence, which is desired in many NLP tasks. Then you can do word-level processing:
newlist = []
for word in word_tokenize(s):
if word.startswith("f") or word.startswith("F"):
newlist.append(word.upper())
else:
newlist.append(word)
The result can be viewed by printing a concatenated string:
>>> print(" ".join(newlist))
The quick brown FOX jumps over the lazy dog .
Upvotes: 0
Reputation: 1434
A string is iterable over its characters, so calling for.. in...
over a string with go over each character. the 'word' is therefore each individual character so there are 4 instances where the 'word' starts with f or e (i.e. there are 3 e's and 1 f in the sentence).
To iterate over the words you need a collection e.g. a list. A list in python is just an ordered collection of items, that has a length and some built in methods.
sentence = "The quick brown fox jumps over the lazy dog."
words = sentence.split(' ') # ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog.']
Lets loop over the words and apply some transformations to them if they meet our criteria:
new_sentence = []
for word in words:
if word.startswith("f") or word.startswith("f"):
new_sentence.append(word.upper())
elif word.endswith("e") or word.endswith("E"):
new_sentence.append("my")
else:
new_sentence.append(word)
print(new_sentence)
# ['my', 'quick', 'brown', 'FOX', 'jumps', 'over', 'my', 'lazy', 'dog.']
result = (' ').join(new_sentence)
# my quick brown FOX jumps over my lazy dog.
To improve this code we might extract the transformations into their own functions:
def transform(word):
if word.startswith("f") or word.startswith("f"):
return word.upper()
elif word.endswith("e") or word.endswith("E"):
return "my"
else:
return word
(' ').join([transform(word) for word in words])
# my quick brown FOX jumps over my lazy dog.
Upvotes: 1
Reputation: 71454
If you want to do something that's based on individual words, you probably want to start by split
ting the sentence:
>>> sentence = "The quick brown fox jumps over the lazy dog."
>>> sentence.split()
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog.']
Now that you have a list of individual words, you can apply logic to those words, e.g. checking if they end in e
:
>>> ['my' if word.endswith('e') else word for word in sentence.split()]
['my', 'quick', 'brown', 'fox', 'jumps', 'over', 'my', 'lazy', 'dog.']
and then you can join
the list back into a single string:
>>> ' '.join('my' if word.endswith('e') else word for word in sentence.split())
'my quick brown fox jumps over my lazy dog.'
In the above example I only handled the 'my'
case. What you will probably want to do is define a function that takes a single word as its argument, applies all the different rules to it, and returns the (transformed) word; then use that function in a split/join
combination like the above.
The key thing is that you need the split/join
to make sure you're applying your function to individual words rather than the whole sentence at once.
Upvotes: 1