Working with strings · Trabalhando com strings
Letters have positions
- A string is a row of characters.
- Each character has a position, called an index.
- Indexes start at
0. Uses[-1]for the last character.
Letras têm posições
- Uma string é uma fileira de caracteres.
- Cada caractere tem uma posição, chamada índice.
- Os índices começam em
0. Uses[-1]para o caractere final.
word = "Python"
print(word[0])
print(word[-1])
Take a slice
- A slice takes part of a string:
s[start:end]. - The character at
endis not included. - Leave a side empty for "from the start" or "to the end":
s[:3],s[2:].
Cortar uma fatia (slice)
- Um slice (fatia) pega parte de uma string:
s[start:end]. - O caractere em
endnão está incluído. - Deixe um lado vazio para "desde o início" ou "até o final":
s[:3],s[2:].
msg = "hello"
print(msg[:3])
print(msg[2:])
Worked example: positions and slices
- In
"banana"the positions areb=0,a=1,n=2,a=3,n=4,a=5. word[0]is the first letter;word[-1]counts back from the end.word[:3]takes positions 0, 1 and 2, and stops before 3.
Exemplo resolvido: posições e slices
- Em
"banana"as posições sãob=0,a=1,n=2,a=3,n=4,a=5. word[0]é a primeira letra;word[-1]conta de trás para frente.word[:3]pega as posições 0, 1 e 2, e para antes de 3.
word = "banana"
print(word[0]) # b
print(word[-1]) # a (the last letter)
print(word[:3]) # ban (positions 0, 1, 2)
print(word[2:5]) # nan (positions 2, 3, 4)
Length and changing case
len(s)gives the number of characters.s.upper()makes a CAPITAL copy;s.lower()makes a lowercase copy.- These make a new string; the original does not change.
Comprimento e troca de casos
len(s)dá o número de caracteres.s.upper()faz uma cópia em MAIÚSCULAS;s.lower()faz uma cópia em minúsculas.- Estas criam uma nova string; a original não muda.
city = "Tokyo"
print(len(city))
print(city.upper())
print(city.lower())
f-strings build text
- An f-string starts with
fbefore the quote. - Put a value inside
{ }and Python drops it into the text. - It is the neat way to mix words and values.
f-strings constroem texto
- Uma f-string começa com
fantes da aspa. - Coloque um valor dentro de
{ }e Python o insere no texto. - É a forma limpa de misturar palavras e valores.
fruit = "apple"
count = 3
print(f"I have {count} {fruit}s")
Common mistakes
- Indexing starts at
0;s[-1]is the last character. - Strings cannot be changed in place — methods like
.upper()return a NEW string, so store the result. - You can only join a string to a string with
+.
Erros comuns
- Indexação começa em
0;s[-1]é o último caractere. - Strings não podem ser alteradas in-place — métodos como
.upper()retornam uma NOVA string, então armazene o resultado. - Só é possível juntar uma string a outra string com
+.
Now you try
- Read the task to see which variable to fill or what to print.
- Press Check answer to test your code.
Agora você tenta
- Leia a tarefa para ver qual variável preencher ou o que imprimir.
- Clique em Check answer para testar seu código.
Index & slice a string · Indexar e fatiar uma string
Each character has an index from 0; a slice · fatia s[a:b] takes a range. · Cada caractere tem um índice a partir de 0; um fatia s[a:b] pega um intervalo.
word is "computer". Store its first · primeiro character in first. Indexes start at 0, so that character is word[0]. · word é "computer". Armazene seu caractere primeiro em first. Os índices começam em 0, então aquele caractere é word[0].
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
first is already the first character of "computer". Store the first four characters in first_four with a slice. word[a:b] stops before b, so four characters is word[:4]. · first já é o primeiro caractere de "computer". Armazene os primeiros quatro caracteres em first_four com um fatiamento. word[a:b] para antes de b, então quatro caracteres é word[:4].
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
phrase is "Hello World". Store its length in n with len(...), and an UPPERCASE copy in loud with .upper(). · phrase é "Hello World". Armazene seu comprimento em n com len(...), e uma cópia em MAIÚSCULAS em loud com .upper().
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
name is "Mia" and · e age is 12. Use an f-string to print exactly: Mia is 12 years old. · name é "Mia" e age é 12. Use uma f-string para imprimir exatamente: Mia is 12 years old.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
first is "ada" and · e last is "lovelace". Store the initials in initials as capital letters, each followed by a dot: "A.L.". · first é "ada" e last é "lovelace". Armazene as iniciais em initials como letras maiúsculas, cada uma seguida por um ponto: "A.L.".
Click Run to see the output here. · Clique em Executar para ver a saída aqui.