Methods of Converting a String of Numbers Separated by Commas to a List of Numbers in Python
Categories: Tech | Pubby Cash Received:
When coding in Python, free conversion of different data types is a skill that one must master. Today, let's talk about one scenario: here is a a string of numbers separated by commas:
numb_str = '1,2,3,4,5'
You need to convert it to a list like this: [1,2,3,4,5]
. How would you do this?
There are multiple ways:
Method 1:
numb_str = '1,2,3,4,5'
numb_str_list = list(numb_str) # Destruct all elements
print(numb_str_list) # Result: ['1', ',', '2', ',', '3', ',', '4', ',', '5']
numb_list = [] # Build an empty list
for item in numb_str_list: # loop over the list
if item.isdigit(): # check if an item is a number
numb_list.append(int(item)) # if yes, convert it to an integer and then append to the list
print(numb_list) # Result: [1, 2, 3, 4, 5]
Method 2:
numb_str = '1,2,3,4,5'
numb_str_list = numb_str.split(',') # Extract the element from the string except the comma
print(numb_str_list) # Result: ['1', '2', '3', '4', '5']
numb_list = [] # Build an empty list
for item in numb_str_list: # loop over the list
numb_list.append(int(item)) # convert it to an integer and then append to the list
print(numb_list) # Result: [1, 2, 3, 4, 5]
Method 3:
numb_str = '1,2,3,4,5'
numb_str_list = numb_str.split(',') # Extract the element from the string except the comma
print(numb_str_list) # Result: ['1', '2', '3', '4', '5']
numb_list = [int(item) for item in numb_str_list] # A concise way of doing method 2
print(numb_list) # Result: [1, 2, 3, 4, 5]
Of the three methods, which one do you like best?
Published from: Pennsylvania US
Liked by: Andy Tang, Evan Tang, fnfOzvSR