def number_of_words_in(text):
return text
text = "She stopped. Turned around. Oops, a bear. Just like that."
x = char(text)
print(text.split())
Hello everyone,
I have to implement a code with output 10, because the amount of words in the text are 10. How can I edit this code, so I get an output of 10. I cant use a loop. And can someone explain to me the split function. Did I do this right?
CodePudding user response:
def number_of_words_in(text):
return len(text.split(" "))
text = "She stopped. Turned around. Oops, a bear. Just like that."
x = number_of_words_in(text)
print(x)
The split
-function splits the given string into a list. It takes the separator as parameter. For example, above the separator is single whitespace (which is also the default value without any parameter).
CodePudding user response:
I believe you want to do this:
def number_of_words_in(text):
return len(text.split())
text = "She stopped. Turned around. Oops, a bear. Just like that."
print(number_of_words_in(text))
which prints: 10
.
CodePudding user response:
Split divides a string into a list where each word is a list item. The default value without any parameter is a white space.
def number_of_words_in(text):
return len(text.split())
text = "She stopped. Turned around. Oops, a bear. Just like that."
print(number_of_words_in(text))
CodePudding user response:
Consider using str.split
inside your function:
def get_number_of_words(text: str) -> int:
return len(text.split())
text = 'She stopped. Turned around. Oops, a bear. Just like that.'
print(f'{text = }')
number_of_words = get_number_of_words(text)
print(f'{number_of_words = }')
Output:
text = 'She stopped. Turned around. Oops, a bear. Just like that.'
number_of_words = 10
CodePudding user response:
def number_of_words_in(text):
return len(text)##returns length of the array.
text="She stopped. Turned around. Oops, a bear. Just like that."
text=text.split()#Converts string into an array of words. ['She', 'stopped.', etc., etc]
print(number_of_words_in(text))
You can do it like this without using loop.