Python 2.8 : String conversion

Cette vidéo détaille la conversion entre chaînes de caractères et entiers en Python. C'est l'un des points qui surprennent le plus les débutants : input renvoie toujours une chaîne, donc pour faire des calculs ou des comparaisons numériques, il faut convertir.

La conversion str vers int

Pour reprendre un exemple : on demande l'âge à l'utilisateur, on veut afficher l'âge plus un, mais le programme plante. La cause : age est une chaîne, donc age + 1 mélange str et int, ce que Python refuse :

age = input("Quel est ton âge ? ")  # age est une str
# print(age + 1)  # erreur : TypeError

# Solution : convertir age en int
age = int(age)
print("L'an prochain vous aurez " + str(age + 1) + " ans")

La fonction int() tente de convertir la chaîne en entier. Si la chaîne contient bien un nombre ("30", "-15", "0"), la conversion réussit. Mais si l'utilisateur tape autre chose (lettre, mot, "vingt"), Python lève une ValueError et le programme plante :

age = int("abc")  # ValueError: invalid literal for int() with base 10: 'abc'

Quelques observations importantes sur la conversion :

  • int("30") fonctionne, retourne 30
  • int("3.5") échoue : il faut int(float("3.5")) pour tronquer
  • int("abc") lève ValueError
  • Une chaîne vide int("") lève aussi ValueError
  • Les espaces sont tolérés autour : int(" 30 ") fonctionne

Pour rendre un programme robuste, on ne peut pas laisser une ValueError casser l'exécution. La solution standard en Python est d'utiliser un bloc try / except qui capture l'exception et permet de gérer proprement le cas d'erreur (afficher un message, redemander la saisie, etc.). C'est exactement le sujet de la prochaine vidéo : la gestion des exceptions et des erreurs.

Summary

This lesson covers the fundamentals of string-to-number conversion in Python, demonstrating how to use explicit conversion syntax (such as int()) to transform character strings into integers. The instructor shows the type mismatch errors that occur when attempting direct operations between strings and numbers, and explains that only strings containing valid numeric characters can be successfully converted. The lesson sets the foundation for the next topic: exception handling to manage conversion failures.

Key points

  • String-to-integer conversion requires explicit syntax using functions like int() rather than implicit automatic conversion
  • Direct concatenation or arithmetic operations between strings and integers result in type errors that halt program execution
  • Only strings that represent valid numeric values (containing digits) can be converted to integers; non-numeric strings cause runtime errors
  • Invalid conversion attempts generate exceptions that must be handled to prevent program crashes
  • Type awareness is essential in Python — understanding when and how to convert between data types is fundamental to writing robust code
  • Exception handling techniques will be needed to gracefully manage conversion failures and invalid input

FAQ

Why can't you directly add a string and an integer in Python?

Python maintains strict type separation — strings and integers are different data types and cannot be automatically combined. You must explicitly convert the string to an integer using the int() function before performing arithmetic or concatenation operations.

What error occurs when you try to convert a non-numeric string to an integer?

The program raises a conversion error because the string does not contain a valid numeric value. For example, attempting int('abc') or int('hello') will fail. This is why exception handling is necessary to prevent program crashes.

How do you properly convert a string to an integer in Python?

Use the built-in int() function with the string as an argument, for example: int('123') returns 123. This conversion works only when the string contains valid numeric digits; any non-numeric characters will cause an error.