• 1
    Entrada y salida de datos
    • Tareas
  • 2
    Condiciones
    • Tareas
  • 3
    Bucle for
    • Tareas
  • 4
    Cadenas de texto
    • Tareas
  • 5
    Bucle while
    • Tareas
  • 6
    Listas
    • Tareas
  • 7
    Matrices 2D
    • Tareas
  • 8
    Diccionarios
    • Tareas
  • 9
    Conjuntos
    • Tareas
  • 10
    Funciones y recursión
    • Tareas
  • к

Lección 4. Lines

Dificultad:

иконка человека красный иконка человека белая иконка человека зеленая Pythonlib

Tarea«NFT»

💻 Python

Imagina que eres el creador de una popular colección NFT y has ideado un nombre único para tu nuevo token. Antes de lanzarlo a la venta, quieres realizar un pequeño análisis técnico del nombre para asegurarte de que cumple con tus "felices" reglas criptográficas. Para ello, necesitas escribir un programa que realice varias operaciones con una línea ingresada.

Tarea:   Escribe un programa que tome una línea (nombre del NFT) y muestre secuencialmente:

  1. El tercer símbolo de esta línea.
  2. El penúltimo símbolo de esta línea.
  3. Los primeros cinco caracteres de esta línea.
  4. Toda la línea, excepto los últimos dos caracteres.
  5. Todos los caracteres con índices pares (indexación desde 0, es decir, el primer, tercer, quinto, etc. símbolos).
  6. Todos los símbolos con índices impares (es decir, el segundo, cuarto, sexto, etc. símbolos).
  7. Todos los caracteres en orden inverso.
  8. Todos los símbolos de la línea en orden inverso, comenzando desde el último.
  9. La longitud total de esta línea.

Cada resultado debe mostrarse en una nueva línea.

Formato de entrada

El nombre para NFT (línea). Se introduce una línea sin espacios o con ellos.

Formato de salida

los resultados del análisis de la línea, cada uno en una nueva línea (solo 9 líneas: 8 de ellas contienen líneas o símbolos, y la última — un número).

Ejemplo

Entrada

Cryptopunks

Salida

y
K
Crypt
Cryptopu
Cytopn
rpo-uks
sknupotpyrc
syptrc
12

Pista

All about strings in Python: from the basics to useful tricks

A string in Python is an ordered sequence of characters. To create a string, it must be enclosed in single ('...'), double ("...") or even triple quotes ("""...""" or "'..."'), which are especially useful for multi-line texts.

The key feature of strings in Python is their immutability. This means that after creating a string, you cannot change its individual characters. Any operation that "modifies" a row actually creates a new one.

string1 = "Hello, World!"
string2 = 'Python is fun'
# Example of a multiline string
multiline_string = """This is a string
that takes
up several lines of code."""

Indexing of rows

Each character in the string has its own unique number, or index. Indexing allows us to access any single character.

It is important to remember: Indexing in Python always starts with 0, not 1. An attempt to access a non-existent index will cause an error IndexError.

w = "Python"
print(w[0]) # Output: P
print(w[1]) # Output: y
print(w[2]) #Output: t
print(w[3]) # Output: h
print(w[4]) # Output: o (not 0, as in the original example)

There is also negative indexing, which is very convenient for accessing characters from the end of a string, where -1 is the last character, -2 is the penultimate, and so on.

print(w[-1]) # Output: n (last character)
print(w[-2]) # Output: o (penultimate character)

Slicing lines

Slices are a powerful tool for extracting a part of a string (substring). They allow you to get not a single character, but a whole range.

General syntax: string[start : end : step]

  • start : the index from which the slice begins (this character is included in the result).
  • end : the index at which the slice ends (this character is not included in the result).
  • step : determines the interval at which characters should be extracted (the default is 1).

Examples of cross-sections

Substring extraction

string = "Hello, World!"
substring = string[0:5] # Characters 0 through 4 inclusive
print(substring) # Output: Hello

Missing starting or ending index If you omit the initial index, the slice will start from the very beginning of the row. If you omit the final one, it will continue to the very end.

string = "Hello, World!"
substring1 = string[:5] # From the beginning to index 5 (not inclusive)
substring2 = string[7:]   # From index 7 to the end of the line
print(substring1) # Output: Hello
print(substring2) # Output: World!

Using a step The step allows you to "jump over" the symbols. For example, step 2 takes every second character.

string = "Hello, World!"
substring = string[::2] # Every second character from the beginning to the end
print(substring) # Output: Hlo ol!

Negative indexes in slices They can be combined to get the parts of the string from the end.

string = "Hello, World!"
substring = string[-6:-1] # We start with the 6th character from the end and go to the 1st from the end.
print(substring) # Output: World

Useful trick: inverting the string The easiest and most popular way to flip a string is to use a slice with a step -1.

string = "Hello, World!"
reversed_string = string[::-1]
print(reversed_string) # Output: !dlroW ,olleH

Adding and multiplying strings

Addition (concatenation) is performed using the + operator. It "glues" the lines into one new one.

str1 = "Hello"
str2 = "World"
result = str1 + ", " + str2 + "!"
print(result) # Output: Hello, World!

Important advice: You cannot add a string with a number directly. To do this, the number must first be converted to a string using the str() function..

# print("Age: " + 25) # Will cause TypeError
print("Age:" + str(25)) # Correct! Output: Age: 25

Multiplication is performed using the * operator, which repeats the string a set number of times. This is useful for creating separators or formatting.

string = "Go"
result = string * 3
print(result) # Output: GoGoGo
print("-" * 20) # Output: --------------------

Useful string operations

String length The built-in len() function returns the number of characters in a string.

my_string = "Hello"
print(len(my_string))  # Will output: 5

Checking for substring occurrence The in and not in operators allow you to check whether one string is contained inside another. The result will be True or False.

Remember: this check is case-sensitive! 'd' and 'D' are different characters.

name = "Daniil"
password = "Qwerty2000!"
print('D' in name) # Outputs: True
print('d' in name) # Outputs: False
print('3' not in password) # Outputs: True

Iterating through characters in a string

The string can be iterated through in the for loop. There are two main ways, and the choice depends on the task.

Method 1: A simple search (more "pythonic") This method is used when you only need the characters of the string themselves. It's simpler and more readable.

a = "1516 the best"
for char in a: # The char variable sequentially takes the value of each character
    if char in "1234567890":
        print(char)

Method 2: Index search This method is needed when not only the symbol itself is important to you, but also its position (index).

a = "1516 the best"
for i in range(len(a)): #i will take values from 0 to len(a)-1
    if a[i] in "1234567890":
print(f"The character '{a[i]}' was found at position {i}")

Conclusion and what's next?

We have reviewed the basic but very important operations.:

  • Indexing to access individual characters.
  • Slices are an incredibly flexible tool for extracting substrings.
  • Concatenation (+) and repetition (*) to create new strings.

This is the foundation upon which all work with text in Python is based. To move on, study the string methods. These are built-in functions that allow you to do even more useful things with strings, for example:

  • .lower() / .upper() reduce the entire string to lowercase or uppercase.
  • .strip() - remove spaces and line breaks at the beginning and at the end.
  • .replace('old', 'new') replace all occurrences of one substring with another.
  • .split() - split a string into a list by separator (for example, by space).
  • .startswith('prefix') / .endswith('suffix') check whether the string begins or ends with a certain sequence of characters.
main.py
Prueba 1
Prueba 2
Prueba 3
Prueba 4
Prueba 5
Prueba 6
Prueba 7
Prueba 8
Prueba 9
Prueba 10
Solución del desarrollador
# Запрашиваем у пользователя строку для анализа
nft_name = input()

# 1) Выводим третий символ этой строки (индекс 2, так как счет начинается с 0)
print(nft_name[2])

# 2) Выводим предпоследний символ этой строки (используем отрицательный индекс -2)
print(nft_name[-2])

# 3) Выводим первые пять символов этой строки (срез от начала до 5-го элемента, не включая его)
print(nft_name[:5])

# 4) Выводим всю строку, кроме последних двух символов (срез от начала до -2 элемента)
print(nft_name[:-2])

# 5) Выводим все символы с четными индексами (срез от начала до конца с шагом 2)
print(nft_name[::2])

# 6) Выводим все символы с нечетными индексами (срез от элемента с индексом 1 до конца с шагом 2)
print(nft_name[1::2])

# 7) Выводим все символы в обратном порядке (срез от начала до конца с шагом -1)
print(nft_name[::-1])

# 8) Выводим все символы через один в обратном порядке (срез от начала до конца с шагом -2)
print(nft_name[::-2])

# 9) Выводим длину данной строки (используем встроенную функцию len)
print(len(nft_name))

🎉 ¡Felicidades! 🎉

¡Has resuelto la tarea brillantemente! Era un reto difícil, pero encontraste la solución correcta. ¡Estás un paso más cerca de dominar la programación! Sigue así, cada etapa superada te hace más fuerte.

AD

Publicidad

red-snake blue-snake green-snake

Ejecutando tu código...

Asistente de IA

¡Hola! Soy tu asistente de programación. Hazme cualquier pregunta sobre Python — puedo explicarte funciones, métodos y ayudarte con la tarea actual.