Check String
Very often it hits that we need to check for the presence of some character or word in the string, and in order to realize this, we should use such a key word as in. As a result, we get a boolean value: True if such a character or substring is present in the string, and False - in the opposite case. For a better understanding, let's look at an example.
9
1
2
3
string = 'Pear Lime Banana'
print('Lime' in string)
print('Mango' in string)
123string = 'Pear Lime Banana' print('Lime' in string) print('Mango' in string)
Tarefa
Swipe to start coding
You have a string. You should check that this line contains such substrings Lorem
, python
, consectetur
.
If there is such a substring, then calculate its length.
Solução
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
string = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
sub_str1 = 'Lorem'
sub_str2 = 'python'
sub_str3 = 'consectetur'
if sub_str1 in string:
print(f'The length of {sub_str1} is {len(sub_str1)}')
else:
print(f'This line does not contain {sub_str1}')
if sub_str2 in string:
print(f'The length of {sub_str2} is {len(sub_str2)}')
else:
print(f'This line does not contain such word as `{sub_str2}`')
if sub_str3 in string:
print(f'The length of {sub_str3} is {len(sub_str3)}')
else:
print(f'This line does not contain {sub_str3}')
Tudo estava claro?
Obrigado pelo seu feedback!
Seção 3. Capítulo 9
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
string = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
sub_str1 = 'Lorem'
sub_str2 = '_ _ _'
sub_str3 = 'consectetur'
if sub_str1 _ _ _ string:
print(_ _ _'The length of {sub_str1} is {_ _ _(sub_str1)}')
_ _ _:
print(_ _ _'This line does not contain {sub_str1}')
_ _ _ sub_str2 __ string:
print(_ _ _'The length of {sub_str2} is {_ _ _(sub_str2)}')
else:
print(_ _ _'This line does not contain such word as `{sub_str2}`')
if _ _ _ in _ _ _:
print(_ _ _'The length of {sub_str3} is {_ _ _(sub_str3)}')
else:
print(_ _ _'This line does not contain {sub_str3}')
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo