Formato de cadena#
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().
def main():
x = 1
y = 5
# Display the variables using .format()
brain.print("Position: ({}, {})".format(x, y))
# VR threads — Do not delete
vr_thread(main)
def main():
# Display a calculation using .format()
brain.print("Sum: {}".format(5 + 3))
# VR threads — Do not delete
vr_thread(main)
def main():
# Display the detected brightness using .format()
brain.print("Brightness: {}%".format(front_eye.brightness(PERCENT)))
# VR threads — Do not delete
vr_thread(main)
Formatting Numbers with .format – Insert values and expressions into a string.
:.xf – Establece la cantidad de decimales a mostrar.
round – Redondea un número a una cantidad determinada de decimales.
:, – Agrega comas como separadores de miles.
:.x% – Convierte un decimal en un porcentaje con x decimales.
:#x – Formatea un número como hexadecimal.
:b – Formatea un número como binario.
Combinación de cadenas: combina texto y valores.
.format() – Combina cadenas y variables en una sola expresión.
Operador+ – Concatena cadenas manualmente con conversión de tipo opcional.
Métodos de cadena: cambian el caso del texto.
upper() – Convierte todos los caracteres a mayúsculas.
lower() – Convierte todos los caracteres a minúsculas.
Comprobación de subcadenas: prueba la presencia o posición del texto.
in – Comprueba si existe una palabra en una cadena.
startswith() – Comprueba si una cadena comienza con un valor dado.
endswith() – Comprueba si una cadena termina con un valor dado.
Secuencias de escape: formatear la salida con caracteres especiales.
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 |
|---|---|
|
La cantidad de decimales a mostrar. |
def main():
# Display pi with 2 decimal places
pi = 3.1415926535
brain.print("Pi: {:.2f}".format(pi))
# Output: Pi: 3.14
# VR threads — Do not delete
vr_thread(main)
Rounding Numbers#
round rounds a number to a specific number of decimal places before formatting.
Usage:
round(number, x)
Parámetros |
Descripción |
|---|---|
|
El número a redondear. |
|
La cantidad de decimales a redondear. |
def main():
# Display a value rounded to only 2 decimal places
value = 5.6789
brain.print("Rounded: {}".format(round(value, 2)))
# Output: Rounded: 5.68
# VR threads — Do not delete
vr_thread(main)
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. |
def main():
# Display a large number separated with commas
number = 1234567
brain.print("Formatted: ")
brain.new_line()
brain.print("{:,}".format(number))
# Output: Formatted: 1,234,567
# VR threads — Do not delete
vr_thread(main)
Percentage#
:.x% formats decimal values as percentages.
Usage:
:.x%
Parámetros |
Descripción |
|---|---|
|
La cantidad de decimales a mostrar. |
def main():
# Display a converted decimal to a percentage
value = 0.875
brain.print("Score: {:.1%}".format(value))
# Output: Score: 87.5%
# VR threads — Do not delete
vr_thread(main)
Hexadecimal#
:#x converts numbers to hexadecimal.
Usage:
:#x
Parámetros |
Descripción |
|---|---|
Este especificador de formato no tiene parámetros. |
def main():
# Convert 255 to hexadecimal
number = 255
brain.print("Hex: {:#x}".format(number))
# Output: Hex: 0xff
# VR threads — Do not delete
vr_thread(main)
Binary#
:b converts numbers to binary (base 2).
Usage:
:b
Parámetros |
Descripción |
|---|---|
Este especificador de formato no tiene parámetros. |
def main():
# Convert 3 to binary
brain.print("Binary: {:b}".format(3))
# Output: Binary: 11
# VR threads — Do not delete
vr_thread(main)
Combinando cadenas#
Puede combinar (o concatenar) cadenas utilizando dos enfoques:
Using .format#
Insert values directly into the string using {}.
def main():
# Display an answer based on the given emotion
emotion = "good"
brain.print("I'm {}, you?".format(emotion))
# VR threads — Do not delete
vr_thread(main)
+ Operator#
Join multiple parts by using +.
Note: Non-strings must first be converted to strings using str().
def main():
# Display the x and y values
x = 10
y = 20
brain.print("X: " + str(x) + ", Y: " + str(y))
# VR threads — Do not delete
vr_thread(main)
Métodos de cadena#
Python proporciona métodos integrados para modificar y comprobar cadenas.
upper#
upper converts all letters in a string to uppercase.
Usage:
upper()
Parámetros |
Descripción |
|---|---|
Este método no tiene parámetros. |
def main():
message = "vexcode"
brain.print(message.upper()) # Output: VEXCODE
# VR threads — Do not delete
vr_thread(main)
lower#
lower converts all letters in a string to lowercase.
Usage:
lower()
Parámetros |
Descripción |
|---|---|
Este método no tiene parámetros. |
def main():
message = "VEXCODE"
brain.print(message.lower()) # Output: vexcode
# VR threads — Do not delete
vr_thread(main)
Comprobación de subcadenas#
in#
in is a keyword that returns a Boolean indicating whether a word exists in a string.
True- The word exists in the string.False- The word does not exist in the string.
def main():
message = "Hey everyone!"
if "Hey" in message:
brain.print("Hello!")
# VR threads — Do not delete
vr_thread(main)
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 |
|---|---|
|
La subcadena a comprobar dentro de la cadena. |
def main():
message = "VR Robot"
if message.startswith("VR"):
brain.print("VR first!")
# VR threads — Do not delete
vr_thread(main)
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:
startswith(substring)
Parámetros |
Descripción |
|---|---|
|
La subcadena a comprobar dentro de la cadena. |
def main():
message = "VR Robot"
if message.endswith("Robot"):
brain.print("Robot last!")
# VR threads — Do not delete
vr_thread(main)
Secuencias de escape#
Las secuencias de escape son caracteres especiales que se utilizan dentro de cadenas para dar formato al texto de salida. Solo están disponibles para su uso con la consola.
New Line#
\n moves text to a new line when printing.
def main():
# Display text on two lines
brain.print("First line\nSecond line")
# VR threads — Do not delete
vr_thread(main)
Tab Spacing#
\t inserts a tab space between words or numbers,
def main():
# Display the quantity of barrels
quantity = 2
brain.print("Boxes:\t", quantity)
# VR threads — Do not delete
vr_thread(main)