Formato de cadenas#

Introducción#

The .format() method in Python is used to create strings that include variables, expressions, or values. This method replaces curly brace placeholders {} in a string with values provided inside .format().

x = 1
y = 5

# Display the variables using .format()
brain.print("Position: ({}, {})".format(x, y))

# Display a calculation using .format()
brain.print("Sum: {}".format(5 + 3))

wait(1, SECONDS)
# Display the time using .format()
brain.print("Time: {}".format(timer.time(SECONDS)))

Formatting Numbers with .format – Insert values and expressions into a string.

  • :.xf – Sets the number of decimal places to show.

  • round – Rounds a number to a given number of decimal places.

  • :, – Adds commas as thousands separators.

  • :.x% – Converts a decimal to a percentage with x decimal places.

  • :#x – Formats a number as hexadecimal.

  • :b – Formats a number as binary.

Combinar cadenas: combina texto y valores.

  • .format() – Combine strings and variables in a single expression.

  • + operator – Concatenate strings manually with optional type conversion.

Métodos de cadena: cambiar mayúsculas y minúsculas del texto.

  • upper() – Converts all characters to uppercase.

  • lower() – Converts all characters to lowercase.

Comprobación de subcadenas: prueba la presencia o la posición del texto.

  • in – Checks if a word exists in a string.

  • startswith() – Checks if a string begins with a given value.

  • endswith() – Checks if a string ends with a given value.

Secuencias de escape: formatean la salida con caracteres especiales.

  • \n – Adds a line break (new line).

  • \t – Adds a tab space between items.

Formatting Numbers with .format#

.format can be used to control how numbers appear, including decimal places, rounding, and other formatting styles such as:

Fixed Decimal Places#

.xf controls how many decimal places a number is displayed with.

Usage:
:.xf

Parámetros

Descripción

x

La cantidad de decimales a mostrar.

# Display pi with 2 decimal places
pi = 3.1415926535
brain.print("Pi: {:.2f}".format(pi))
# Output: Pi: 3.14

Rounding Numbers#

round rounds a number to a specific number of decimal places before formatting.

Usage:
round(number, x)

Parámetros

Descripción

number

El número a redondear.

x

La cantidad de decimales a los que redondear.

# Display a value rounded to only 2 decimal places
value = 5.6789
brain.print("Rounded: {}".format(round(value, 2)))
# Output: Rounded: 5.68

Thousands Separator#

:, inserts commas as thousands separators to make large numbers more readable.

Usage:
:,

Parámetros

Descripción

Este especificador de formato no tiene parámetros.

# Display a large number separated with commas
number = 1234567
brain.print("Formatted: ")
brain.print("{:,}".format(number))
# Output: Formatted: 1,234,567

Percentage#

:.x% formats decimal values as percentages by multiplying the value by 100 and adding a percent sign.

Usage:
:.x%

Parámetros

Descripción

x

La cantidad de decimales a mostrar.

# Display a converted decimal to a percentage
value = 0.875
brain.print("Score: {:.1%}".format(value))
# Output: Score: 87.5%

Hexadecimal#

:#x converts numbers to hexadecimal.

Usage:
:#x

Parámetros

Descripción

Este especificador de formato no tiene parámetros.

# Convert 255 to hexadecimal
number = 255
brain.print("Hex: {:#x}".format(number))
# Output: Hex: 0xff

Binary#

:b converts numbers to binary (base 2).

Usage:
:b

Parámetros

Descripción

Este especificador de formato no tiene parámetros.

# Convert 3 to binary
brain.print("Binary: {:b}".format(3))
# Output: Binary: 11

Combinando cadenas#

Puedes combinar (o concatenar) cadenas utilizando dos métodos:

Using .format#

Insert values directly into the string using {}.

# Display an answer based on the given emotion
emotion = "good"
brain.print("I'm {}, you?".format(emotion))

+ Operator#

Join multiple parts by using +.

Note: Non-strings must first be converted to strings using str().

# Display the x and y values
x = 10
y = 20
brain.print("X: " + str(x) + ", Y: " + str(y))

Métodos de cadena#

Python proporciona métodos integrados para modificar y comprobar cadenas de caracteres.

upper#

upper converts all letters in a string to uppercase.

Usage:
upper()

Parámetros

Descripción

Este método no tiene parámetros.

# Capitalize a string with .upper()
message = "vexcode"
brain.print(message.upper())  # Output: VEXCODE

lower#

lower converts all letters in a string to lowercase.

Usage:
lower()

Parámetros

Descripción

Este método no tiene parámetros.

# Make a string lowercase with .lower()
message = "VEXCODE"
brain.print(message.lower())  # Output: vexcode

Comprobación de subcadenas#

in#

in is a keyword that returns a Boolean indicating whether a substring (word or piece of text) exists in a string.

  • True – The word exists in the string.

  • False – The word does not exist in the string.

message = "Hey everyone!"
if "Hey" in message:
    brain.print("Hello!")

startswith#

startswith returns a Boolean indicating whether a string begins with a given value.

  • True – The word starts the string.

  • False – The word does not start the string.

Usage:
startswith(substring)

Parámetros

Descripción

substring

La subcadena que se debe comprobar al principio de la cadena.

# Check for 'CTE' at the start of a string
message = "CTE Robot"

if message.startswith("CTE"):
    brain.print("CTE first!")

endswith#

endswith returns a Boolean indicating whether a string ends with a given value.

  • True – The word ends the string.

  • False – The word does not end the string.

Usage:
endswith(substring)

Parámetros

Descripción

substring

La subcadena que se debe comprobar al final de la cadena.

# Check for `Robot` at the end of a string
message = "CTE Robot"

if message.endswith("Robot"):
    brain.print("Robot last!")

Secuencias de escape#

Las secuencias de escape son caracteres especiales que se utilizan dentro de las cadenas de texto para dar formato a la salida de texto.

New Line#

\n moves text to a new line when printing.

# Display text on two lines
brain.print("First line\nSecond line")

Tab Spacing#

\t inserts a tab space between words or numbers.

# Display the quantity of disks
quantity = 2
brain.print("Disks:\t", quantity)