
Python 中的 len() Function is super convenient,Are you in the process is often used when a function.len()Input is a sequence or a collection of,當函數被調用時,It returns the length of the.你可以使用 len() To get you in Python Anything you want in the length of the.例如,It can be used for string、列表、Figure and a dictionary.另一個使用 len() A good example of this is with loop or range() 函數結合使用.現在讓我們看看使用len()函數的幾種方法.
首先很簡單,我們可以用**len()**To check the length of a string.The following are examples of a few do this.
print(len(''))
復制代碼0
復制代碼print(len(' '))
復制代碼1
復制代碼print(len('Hi!'))
復制代碼3
復制代碼print(len('This string is a little longer.'))
復制代碼31
復制代碼print(len('Python'))
復制代碼6
復制代碼print(len('Programming'))
復制代碼11
復制代碼print(len('[email protected]#$'))
復制代碼4
復制代碼my_name = 'Vegibit'
print('The length of your name is: ', end='')
print(len(my_name))
復制代碼The length of your name is: 7
復制代碼best_language_ever = 'Python'
print(len(best_language_ever))
復制代碼6
復制代碼在下面的例子中,We will be a string of Numbers stored as a string,To indicate that the zip code.我們可以使用len()To determine the length of the zip code is correct.Because all the zip need to be5個字符的長度,我們可以使用len()To determine if a given zip code is valid or invalid.
zip_code = '10001'
if len(zip_code) == 5:
check = 'Valid'
else:
check = 'Invalid'
print(check)
復制代碼Valid
復制代碼zip_code = '1234567'
if len(zip_code) == 5:
check = 'Valid'
else:
check = 'Invalid'
print(check)
復制代碼Invalid
復制代碼zip_code = '94088'
check = 'Valid' if len(zip_code) == 5 else 'Invalid'
print(check)
復制代碼Valid
復制代碼在 Python 中處理列表時,len() Function is super useful.In simple and complex applications,There are countless examples show that you need to know the length of a list.下面是幾個使用 len() With the list of examples of.
animals = ['rabbit', 'dog', 'moose']
print(len(animals))
復制代碼3
復制代碼sodas = ['Coke', 'Pepsi', 'Sprite']
print(len(sodas))
復制代碼3
復制代碼quarterly_revenues = [15000, 12000, 9000, 20000]
print(len(quarterly_revenues))
復制代碼4
復制代碼stock_prices = [343.26, 89.25]
print(len(stock_prices))
復制代碼2
復制代碼user_settings = [True, False, False, True, False]
print(len(user_settings))
復制代碼5
復制代碼dog_names = []
while True:
print('What is dog name number ' + str(len(dog_names) + 1) + '? ("q" to quit):')
name = input()
if name == 'q':
break
dog_names = dog_names + [name]
print('You entered ' + str(len(dog_names)) + ' dog names.')
print('Here they are for you:')
for name in dog_names:
print(' ' + name)
復制代碼What is dog name number 1? ("q" to quit):
Moe
What is dog name number 2? ("q" to quit):
Buddy
What is dog name number 3? ("q" to quit):
Winnie
What is dog name number 4? ("q" to quit):
q
You entered 3 dog names.
Here they are for you:
Moe
Buddy
Winnie
復制代碼在下面的例子中,We have a list of the tools in the yard.We can cycle on each yard tools name,並使用 len() The length of a function to print out each tool.
yard_tools = ['Snow blower', 'Tractor', 'Lawn Mower']
for yard_tool in yard_tools:
print(yard_tool + ' has ' + str(len(yard_tool)) + ' characters')
復制代碼Snow blower has 11 characters
Tractor has 7 characters
Lawn Mower has 10 characters
復制代碼我們可以用 Simpsons 和 f-strings 做類似的事情.
the_simpsons = ['Homer', 'Marge', 'Bart', 'Lisa', 'Maggie']
for character in the_simpsons:
print(f'{character} has a total of {len(character)} characters.')
復制代碼Homer has a total of 5 characters.
Marge has a total of 5 characters.
Bart has a total of 4 characters.
Lisa has a total of 4 characters.
Maggie has a total of 6 characters.
復制代碼len() 函數在 Python 的列表理解Also is very good.
rivers = ['Amazon', 'Nile', 'Yangtze']
print([len(river) for river in rivers])
復制代碼[6, 4, 7]
復制代碼This example shows how to len() 函數與 Python range() 函數一起使用.這是一種有用的方法,Because the cycle of code can access the variable i Index and the index of value.使用 len() 和 range() 的好處是,How many items no matter list,The code can be accurately iterative them,Without the need to counter.
gifts = ['Gaming PC', 'Ceiling Fan', 'Nintendo Watch']
for i in range(len(gifts)):
print('Index ' + str(i) + ' in gifts is: ' + gifts[i])
復制代碼Index 0 in gifts is: Gaming PC
Index 1 in gifts is: Ceiling Fan
Index 2 in gifts is: Nintendo Watch
復制代碼請注意,When we change the list size here,Code still can correctly handle it.
gifts = ['Gaming PC', 'Ceiling Fan', 'Nintendo Watch', 'More Gifts!', 'Even More Gifts!!']
for i in range(len(gifts)):
print('Index ' + str(i) + ' in gifts is: ' + gifts[i])
復制代碼Index 0 in gifts is: Gaming PC
Index 1 in gifts is: Ceiling Fan
Index 2 in gifts is: Nintendo Watch
Index 3 in gifts is: More Gifts!
Index 4 in gifts is: Even More Gifts!!
復制代碼len()Function of the ingenious use of let we can calculate to aPythonThe number of file on the command line parameters.We can calculate all the total length of the command line parameters.
import sys
# printing the number of arguments
print(f'You passed {len(sys.argv[1:])} arguments to the {sys.argv[0]} file.')
# adding the length of all command line arguments
word_lengths = 0
for arg in sys.argv[1:]:
word_lengths += len(arg)
print(f'The total length of all command-line arguments is {word_lengths}')
復制代碼PS C:\Python> python testing.py 1 2
You passed 2 arguments to the testing.py file.
The total length of all command-line arguments is 2
PS C:\Python> python testing.py 'hi' 'ho' 'silver'
You passed 3 arguments to the testing.py file.
The total length of all command-line arguments is 10
復制代碼你也可以將 len() 函數與 tuple、dictionary 和 set 數據類型一起使用.這裡有幾個例子.
# len of tuples
eggs = ('hello', 42, 0.5, True, False)
print(len(eggs))
復制代碼5
復制代碼# len of dictionaries
ice_cream_preferences = {
'Ben': 'Chocolate',
'Jerry': 'Vanilla',
'Sandy': 'Cookie Dough',
'Mary': 'Black Rasberry'
}
print(len(ice_cream_preferences))
復制代碼4
復制代碼# len of sets
stocks = {'MSFT', 'FB', 'IBM', 'FB'}
print(len(stocks))
復制代碼3
復制代碼We have seen a lot about how to use in different ways len() 函數的例子.You will find yourself on your Python In the program have been using this convenient function.