Python splits the text and puts into an array

I really don't know how to explain this using English, but:

inputText = "John Smith 5" 

I want to split it and paste it in nameArray and make 5 (string) into an integer.

 nameArray = ["John", "Doe", 5] 

And then put the name Array in fullNameArray

 fullNameArray = [["John", "Doe", 5], ["John", "Smith", 5]] 
+4
source share
3 answers

Use exception handling and int() here:

 >>> def func(x): ... try: ... return int(x) ... except ValueError: ... return x ... >>> inputText = "John Smith 5" >>> spl = [func(x) for x in inputText.split()] >>> spl ['John', 'Smith', 5] 

If you are sure that this is always the last item to be converted, try the following:

 >>> inputText = "John Smith 5" >>> spl = inputText.split() >>> spl[-1] = int(spl[-1]) >>> spl ['John', 'Smith', 5] 

use nameArray.append to add a new list to it:

 >>> nameArray = [] #initialize nameArray as an empty list >>> nameArray.append(["John", "Doe", 5]) #append the first name >>> spl = [func(x) for x in inputText.split()] >>> nameArray.append(spl) #append second entry >>> nameArray [['John', 'Doe', 5], ['John', 'Smith', 5]] 
+3
source

you are looking for nameArray = inputText.split()

The following code will work for any number on your line

therefore, it is assumed that the inputs are in a list called inputTextList:

 fullNameArray = [] for inputText in inputTextList: nameArray = inputText.split() nameArray = [int(x) if x.isdigit() else x for x in nameArray] fullNameArray.append(nameArray) 
+2
source
 >>> fullnameArray = [["John", "Doe", 5]] >>> inputText = "John Smith 5" >>> fullnameArray.append([int(i) if i.isdigit() else i for i in inputText.split()]) >>> fullnameArray [['John', 'Doe', 5], ['John', 'Smith', 5]] 

The third line with a conditional expression ("ternary operator") inside > (if you are not familiar with this syntax) can also be written as:

 nameArray = [] for i in inputText.split(): if i.isdigit(): nameArray.append(int(i)) else: nameArray.append(i) fullnameArray.append(sublist) 
+1
source

Source: https://habr.com/ru/post/1486462/


All Articles