Supprimer Rendre public Rendre privé Add tags Delete tags
  Ajouter un tag   Annuler
  Supprimer le tag   Annuler
  • • DevOps notes •
  •  
  • AI
  • Tags
  • Connexion

Numbers, strings/shaare/R2PqPQ

  • python
  • python

Numbers (int and float)

  • int: Whole numbers (e.g., 10, 1024). No overflow due to arbitrary precision.
  • float: Numbers with decimals (e.g., 3.14159). Uses IEEE 754 representation; small precision differences possible.
import math

print(type(1.0))

print("When comparing floats directly, we may run into precision issues:")
print("0.1 * 3 == 0.3: ", 0.1 * 3 == 0.3)
print("To tackle this, we can use the math.isclose() function:")
print("math.isclose(0.1 * 3, 0.3): ", math.isclose(0.1 * 3, 0.3))

Arithmetic Operations

  • +, -, *, /
  • / true division → float
  • // floor division → integer or float
  • % modulo → remainder
  • ** → power
print(8/2)
print(type(8/2))
print(5/3)
print(8//2)
print(type(8//2))
print(5//3)
print(5//3.0)
print(5%3) # 1 as the result, and 2 remaining

Strings

String Manipulation

  • Strings are ordered, immutable sequences of characters.
  • Use single or double quotes consistently; triple quotes for multi-line strings or docstrings.
single_line_str = "Double quoted"
single_line_str2 = 'Single quoted'

command_template = """
I will not be indented
    I will be indented
"""

print(command_template)

Format Output using f-string

Tip: f-strings allow inline expression evaluation and formatting, making string construction concise and readable.

math_division = 7/2
print(f"Result: {math_division}")
print(f"Result: {7/2}")

Common Operations and Essential String Methods

  • Concatenation (+): Joins strings.
  • Length (len()): Gets the number of characters.
  • Indexing ([]): Access a character by position (0-based).
  • Slicing ([:]): Extract substrings.
  • .lower() / .upper()
  • .strip() / .lstrip() / .rstrip()
  • .startswith() / .endswith()
  • .split() / .join()
  • .replace()
course_title = "     Python strings    "
print(course_title)
print(f"Result of .strip(): {course_title.strip()}")
print(f"Result of .lstrip(): {course_title.lstrip()}")
print(f"Result of .rstrip(): {course_title.rstrip()}")
print(f"Result of .upper(): {course_title.upper()}")
print(f"Result of .lower(): {course_title.lower()}")

filename = "file.yaml"
print(filename.startswith("file"))
print(filename.endswith("yaml"))

path = "/usr/local/bin"
path_parts = path.split("/")
print(f"path parts: {path_parts}")
print(f"joined path paths: {"\\".join(path_parts)}")

print(path + "/python")
print(len(path))
print(path[3])
print(path[3:10])
print(path[3:])
print(path[:10])

String Immutability

Strings are immutable, meaning you cannot change a string in place; operations that seem to modify a string actually create and return a new string object.

course_title = "     Python strings    "
print(course_title)
print(f"Result of .strip(): {course_title.strip()}")
print(f"Result of .lstrip(): {course_title.lstrip()}")
print(f"Result of .rstrip(): {course_title.rstrip()}")
print(f"Result of .upper(): {course_title.upper()}")
print(f"Result of .lower(): {course_title.lower()}")
print(course_title)
3 months ago Permalien
cluster icon
  • Signaling Errors: The raise Statement : Signaling Errors: The raise Statement Functions sometimes encounter states they cannot handle and must signal failure clearly. Using raise triggers...
  • List : Lists (list) Lists are ordered, mutable sequences defined with square brackets []. You can add, remove, or change items after creation. Characteristic...
  • Logging to Files : Logging to Files Basic File Logging with FileHandler Use logging.FileHandler to write log records to a file. mode='a' (append) preserves existing log...
  • Adding Tests to a Multi-File Project : Adding Tests to a Multi-File Project Standard Project Layout with Tests To maintain a clean and organized codebase, it is standard practice to separat...
  • Configuring Pytest : Configuring Pytest As you start using Pytest extensively, typing -v or -m on the command line every time becomes tedious. Centralize your defaults in...


(110)
Filtrer par liens sans tag
Replier Replier tout Déplier Déplier tout Êtes-vous sûr de vouloir supprimer ce lien ? Êtes-vous sûr de vouloir supprimer ce tag ? Le gestionnaire de marque-pages personnel, minimaliste, et sans base de données par la communauté Shaarli