4

I dont really know how to explain it using english but:

inputText = "John Smith 5"

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

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

And then place nameArray to fullNameArray

fullNameArray = [["John", "Doe", 5], ["John", "Smith", 5]]

3 Answers 3

3

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're sure it's always the last element that has to be converted then try this:

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

use nameArray.append to append the 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]]
Sign up to request clarification or add additional context in comments.

4 Comments

I used your second code but now my problem is I cannot populate the list as (spl =)... is there away to use append into spl aswell as splitting?
@BlupDitzz your nameArray must be a list of lists to get the desired output.
I get my desired output when I only input one name. When I input a second name, the second name is the one that is only printed
@BlupDitzz I've updated my code, try to do something like that.
2

you are looking for nameArray = inputText.split()

The following code will work for any number in your string

so assuming 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)

Comments

1
>>> 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 the conditional expression ("ternary operator") inside a list comprehension (in case you're unfamiliar with that 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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.