Manipulação de strings no Python
Este artigo explica a manipulação de strings no Python.
Você pode aprender sobre várias manipulações de strings, como criar e concatenar strings, buscar e substituir, junto com exemplos de código.
YouTube Video
Manipulação de strings no Python
Existem várias maneiras de manipular strings no Python. Abaixo está uma introdução às operações de string mais comuns.
Criando strings
Em Python, strings podem ser criadas usando aspas simples ('
), aspas duplas ("
) ou aspas triplas ('''
, """
).
1single_quoted = 'Hello'
2double_quoted = "World"
3multi_line = '''This is
4a multi-line
5string'''
6
7print(single_quoted)
8print(double_quoted)
9print(multi_line)
- Este código demonstra como criar e exibir strings em Python usando aspas simples, aspas duplas e aspas triplas.
Concatenação de strings
Para concatenar strings, use o operador +
, as f-strings
ou o método str.format
.
1# + operator
2name = "John"
3greeting = "Hello, " + name + "!"
4print(greeting)
5
6# f-string (available in Python 3.6 and above)
7greeting_f = f"Hello, {name}!"
8print(greeting_f)
9
10# str.format method
11greeting_format = "Hello, {}!".format(name)
12print(greeting_format)
- Este código mostra como concatenar strings em Python usando o operador
+
, f-strings e o métodostr.format
.
Repetindo strings
Para repetir strings, use o operador *
.
1repeat = "ha" * 3 # Result: "hahaha"
2print(repeat)
- Este código demonstra como repetir strings em Python usando o operador
*
.
Comprimento de uma string
Para obter o comprimento de uma string, use a função len
.
1name = "John"
2greeting = "Hello, " + name + "!"
3
4# Returns the length of the string greeting
5length = len(greeting)
6print(length)
- Este código mostra como obter o comprimento de uma string em Python usando a função
len
.
Indexação e fatiamento
Use indexação ou fatiamento para obter caracteres específicos ou substrings dentro de uma string.
1word = "Python"
2
3first_char = word[0] # P
4last_char = word[-1] # n
5print(first_char)
6print(last_char)
7
8# Slice
9sliced_word = word[1:4] # yth
10reversed_word = word[::-1] # nohtyP
11print(sliced_word)
12print(reversed_word)
- Este código demonstra como recuperar caracteres ou substrings específicos de uma string em Python usando indexação e fatiamento.
Processando cada caractere
Como as strings são tratadas como tipos de sequência, você pode processar cada caractere usando um loop for
.
1text = "Python"
2
3# Iterate each character
4for char in text:
5 print(char)
- {^ i18n_speak
このコードは、文字列
Python
を1文字ずつ取り出して順番に表示する方法を示しています。^}
Busca e substituição em strings
Use os métodos str.find
e str.replace
para buscar e substituir em strings.
1sentence = "She sells sea shells on the sea shore."
2
3# Returns the index of the first occurrence of "sea": 10
4index = sentence.find("sea")
5print(index)
6
7# Replace "sea" with "ocean"
8replaced_sentence = sentence.replace("sea", "ocean")
9print(replaced_sentence)
- Este código mostra como pesquisar uma string usando o método
str.find
e substituir uma string usando o métodostr.replace
em Python.
Convertendo a capitalização em strings
Para converter strings para maiúsculas ou minúsculas, use str.upper
, str.lower
, str.capitalize
ou str.title
.
1text = "hello world"
2upper_text = text.upper() # "HELLO WORLD"
3lower_text = text.lower() # "hello world"
4capitalized_text = text.capitalize() # "Hello world"
5title_text = text.title() # "Hello World"
6
7print(upper_text)
8print(lower_text)
9print(capitalized_text)
10print(title_text)
- Este código demonstra como converter strings para maiúsculas, minúsculas e título em Python.
Dividindo e unindo strings
Para dividir uma string por um delimitador específico, use str.split
, e para unir elementos de uma lista, use str.join
.
1csv = "apples,bananas,cherries"
2fruits = csv.split(",") # ["apples", "bananas", "cherries"]
3joined_fruits = ", ".join(fruits) # "apples, bananas, cherries"
4
5print(fruits)
6print(joined_fruits)
- Este código mostra como dividir uma string usando
str.split
e juntar elementos de listas usandostr.join
em Python.
Removendo espaços em branco
Para remover espaços em branco de uma string, use str.strip
, str.lstrip
ou str.rstrip
.
1whitespace = " hello "
2stripped = whitespace.strip() # "hello"
3lstripped = whitespace.lstrip() # "hello "
4rstripped = whitespace.rstrip() # " hello"
5
6print(stripped)
7print(lstripped)
8print(rstripped)
- Este código demonstra como remover espaços em branco do início e do final ou de um dos lados de uma string em Python usando
str.strip
,str.lstrip
estr.rstrip
.
Resumo
Ao combinar essas operações, várias manipulações de strings podem ser realizadas no Python.
Você pode acompanhar o artigo acima usando o Visual Studio Code em nosso canal do YouTube. Por favor, confira também o canal do YouTube.