Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

268
Visualizações
Syntax for returning the entire list when using the minus sign?

Python lists have nifty indexing/slicing capabilities. Here are several examples:

x = "123456"

x[:-3]
'123'

x[:-1]
'12345'  # -1 slices off last element

x[:-0]  # -0 slices off .. everything .. this is what i'd like to fix
''

I would like to slice off a variable number of elements d:

x[:-d]

But if d were 0 we get a much different result than desired. A workaround is:

d = 0
x[:-d if d else len(x)]
'123456'

That is possible - but is there any [shorter] alternative?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

The issue you're hitting is that -0 is the same as 0, and x[0:0] is an empty slice.

I'd suggest:

x[:len(x)-d]
over 4 years ago · Santiago Trujillo Relatório

0

You could use None, which is the default for missing start/stop/step values:

x[:-d or None]
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda