Strings Have Length
There is also a very useful function in Python that can give the length of a string -- len()
function.
Let's look at the example of using this function.
9
1
2
3
string = 'watermelon'
length = len(string)
print(f'the length of the string "{string}" is {length}')
123string = 'watermelon' length = len(string) print(f'the length of the string "{string}" is {length}')
Uppgift
Swipe to start coding
You have such strings apple
,grape
, orange
.
You have to get the length of each of these strings. Using such comparison operators
>, <
determine the longest string.
Lösning
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
str_1 = 'apple'
str_2 = 'grape'
str_3 = 'orange'
len_1 = len(str_1)
len_2 = len(str_2)
len_3 = len(str_3)
print(f'str_1 is greater than str_2? {str_1 > str_2}')
print(f'The length of str_1 is {len_1}, the length of str_2 is {len_2}')
print(f'str_1 is greater than str_3? {str_1 > str_3}')
print(f'The length of str_1 is {len_1}, the length of str_3 is {len_3}')
print(f'str_2 is greater than str_3? {str_2 > str_3}')
print(f'The length of str_2 is {len_2}, the length of str_3 is {len_3}')
Var allt tydligt?
Tack för dina kommentarer!
Avsnitt 3. Kapitel 8
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
str_1 = 'apple'
str_2 = 'grape'
str_3 = 'orange'
len_1 = _ _ _
len_2 = _ _ _
len_3 = _ _ _
print(f'str_1 is greater than str_2? {str_1 _ _ _ str_2}')
print(_ _ _'The length of str_1 is {_ _ _}, the length of str_2 is {_ _ _}')
print(f'str_1 is greater than str_3? {_ _ _}')
print(_ _ _'The length of str_1 is {_ _ _}, the length of str_3 is {_ _ _}')
print(f'str_2 is greater than str_3? {_ _ _}')
print(_'The length of str_2 is {_ _ _}, the length of str_3 is {_ _ _}')
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal