dog = 'penny'
print(dog.title())
dog_names = ['pete', 'luke', 'shane']
print(dog_names.remove('shane'))
Why does Python return an output of Penny
for dog.title()
but None
for dog_names.remove('shane')
? Why can I not print the list dog_name
with the method remove
while I can use the method title
on dog
?
I understand that I get None
because dog_name.remove
has no return, but how does dog.title
have a return?
The title()
function is a pre-defined function in Python which is used to covert the first character of the string into uppercase and the remaining characters into lowercase and return a new string. in your example if you run print(dog)
you can see that penny
is all lowercase, but if you run print(dog.title())
you can see that the first letter in Penny
which is P
is uppercase and the remaining is lowercase
In order to answer your question, first, you need to understand what's being returned.
When calling print
on a function or method, it will display the returned value. With that being said, you can check the return value of both functions from the documentation
https://docs.python.org/2/tutorial/datastructures.html#more-on-lists
list.remove(x) Remove the first item from the list whose value is x. It is an error if there is no such item.
https://docs.python.org/3.7/library/stdtypes.html#str.title
str.title() Return a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase.
title()
returns the titled case string, that's why it's printed.remove()
doesn't return anything, in this case, python has a default return value of None
( Source ) that's why it's printed when calling remove()
A function
/ method
in any programming language performs a specific task. A task could be performed on the inputs passed to the function. After performing the task, the function may want to give the result back to the caller of the function. It may do that by:
remove()
method of list data type) title()
method) Your remove() method doesn't return anything back to the caller. Instead it just deletes an element from the list. To print the list after removing an element:
dog_names.remove('shane')
print(dog_names)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.