Type Casting

Beginning Python Programming

Makzan, 2020 April.

Type Casting

  • Converting between string and integer
  • Converting between List and Set

When to convert type?

  • Inputs are always string, we need to convert numeric input into integer.
  • Data fetching from the web may be string but we need integer or float type.
  • We need string representation of the data
  • We need to convert between collection types, such as list to set.

Converting String ⮂ Integer

age = input("What is your age? ")
age = int(age)
print(type(age))

# Result:
> What is your age? 32
> <class 'int'>

Converting List Set

L = [1,2,3,3,3,4,5]
S = set(L)
print(S)
print(list(S))

# Result:
> {1, 2, 3, 4, 5}
> [1, 2, 3, 4, 5]

Type Casting

Summary

# Convert to int
int('123')
int(123.0)

# Convert to float
float('123.4')
float(123)

# Convert to string
str(123)

# Convert to list
list({1,2,3,4})

# Convert to set
set([1,2,3,3,3])