Different types of data conversion in python

Posted by progman on Mon, 10 Jan 2022 22:25:57 +0100

Data conversion: the process of changing one's own data type into a new data type and having all the functions of the new type is data conversion

1. String and number conversion:

  • When converting a string to a number, it must be a string composed of numbers
  • Convert numbers to strings, no requirements
  • Conversion of integer and floating-point type to string: str function
  • Convert string to integer: int function
  • Convert string to floating point: float function

Example:

number1 = 123
number2 = 123.11
str1 = '88'
str2 = '66.10'

# Convert numeric type to string
number1_str = str(number1)
number2_str = str(number2)

# Convert string to numeric type
str1_int = int(str1)
str2_float = float(str1)
print('Convert integer to string:{}'.format(type(number1_str)))
print('Convert float to string:{}'.format(type(number2_str)))
print('Convert string to integer:{}'.format(type(str1_int)))
print('Convert string to floating point:{}'.format(type(str2_float)))

result:

2. String and list conversion

String to list: split function

  • Cut the string into a list with certain rules
  • string.split(sep=None, maxsplit=-1)
  • sep: regular symbol for cutting. If it is not added, the default space is used. If there is no space in the string, the list is generated without segmentation
  • Maxplit: cut according to the cutting symbol. At this time, the default is - 1, unlimited
  • Returns a list

Example:

a = '123'
b = '1 2 3'
c = '1,22,3'

# For a string without spaces, the whole string is converted into a list as an element
print(a.split())

# There are spaces, which are divided into lists. There are 2 spaces, which are divided into 3 elements
print(b.split())

# Set the comma of the split symbol and split it only once. Here, it will be split once and become two elements
print(c.split(',', 1))

result:

Convert list to string: join function

  • Convert the list into a string with certain rules
  • 'sep'.join(iterable)
  • sep: regular symbols for generating strings
  • iterable: a list or tuple or collection of non numeric types
  • Returns a string
  • Only string type lists can use join, otherwise an error will be reported

Example:

test = ['b', 'c', 'a']
print('List:{}'.format(test))

# Use join to convert the list into a string, and use each element as a string separate
# 
new_test1 = '.'.join(test)
print('use join Convert to string:{}'.format(new_test1))

# sorted can sort any type of data. Sort in the previous listology is a built-in function of the list. Only category types can be used
test2 = sorted(test)  # Using sorted
print('use sorted Sort list:{}'.format(test2))

result:

You can use sorted to sort strings: strings will be converted into lists while sorting. At this time, you can use join to convert lists into strings

Example:

test = 'bca'
print('character string:{}'.format(test))

new_test = sorted(test)  # Sort using sorted
print('String sort, but converted to list:{}'.format(new_test))

str_test = ''.join(new_test)  # Convert list to string
print('Convert list to string:{}'.format(str_test))

result:

3. Conversion between string and bytes

  • Bytes type: binary data stream, which can be understood as a special string; The string type preceded by b indicates the bytes type

Example:

a = 'my name is mike'
b = b'my name is mike'

print('{}: Data type:{}'.format(a, type(a)))
print('{}: Data type:{}'.format(b, type(b)))

# The bytes type is a special string type that uses all the built-in functions of the string
print('take bytes Type variable initials become uppercase:{}'.format(b.capitalize()))

# Note that the bytes type variable uses the function. If there are parameters in the function, note that the parameters in the function should also be bytes type
print('take bytes Replace elements of type variables:{}'.format(b.replace(b'mike', b'haha')))
print('take bytes Type variable for cutting:{}'.format(b[:7]))

result:

You can use the dir function to see which functions the variable has:

Example:

b = b'my name is mike'

print(dir(b))

result:

Convert string to bytes: use the function encode

  • Usage: string encode(encoding=‘utf-8’, errors-'strict)
  • Encoding: converted encoding format, such as ascii, gbk and default utf-8
  • errors: the processing method when an error occurs. The default is strict. You can throw the error directly, or you can choose ignore to ignore the error
  • Returns data of type bytes

Convert bytes to string type: use the function decode

  • Usage: bytes encode(encoding=‘utf-8’, errors-'strict)
  • Encoding: converted encoding format, such as ascii, gbk and default utf-8
  • errors: the processing method when an error occurs. The default is strict. You can throw the error directly, or you can choose ignore to ignore the error
  • Returns data of a string type

Example:

a = 'my name is Zhang San'
print('{}: Data type:{}'.format(a, type(a)))

# Convert string to bytes
bytes_a = a.encode('utf-8')
print('{}: Data type:{}'.format(bytes_a, type(bytes_a)))

# Convert bytes to string
str_a = bytes_a.decode('utf-8')
print('{}: Data type:{}'.format(str_a, type(str_a)))

result:

4. Conversion of lists, sets and tuples

Example:

test = ['a', 'b', 'c']
set_test = set(test)  # Convert list to collection
tuple_test = tuple(test)  # Convert list to tuple
print('List:{}'.format(test))
print('Convert list to collection:{}'.format(set_test))
print('Convert list to tuple:{}'.format(tuple_test))


test1 = (1, 'a', '!')
set_test1 = set(test1)  # Tuple to set
list_test1 = list(test1)  # Tuple to list
print('Tuple:{}'.format(test1))
print('Tuple to set:{}'.format(set_test1))
print('Tuple to list:{}'.format(list_test1))


test2 = {'aa', 123, 'k'}
list_test2 = list(test2)  # Convert collection to list
tuple_test2 = tuple(test2)  # Convert set to tuple
print('Set:{}'.format(test2))
print('Convert collection to list:{}'.format(list_test2))
print('Convert set to tuple:{}'.format(tuple_test2))

result:

Topics: Python