-3

Say I have the following string:

    string1 = 'Twenty 20 Twelve 12'

I would like to convert it into a list that would keep words as strings in separate elements, and numbers in another (as integers):

    list1 = ['Twenty', 20, 'Twelve', 12]

My current code looks is:

    list1 = [y for y in string1.replace(' ','')]

and the result prints out as:

    ['T','w','e','n','t','y','2','0','T','w','e','l','v','e','1','2']

How would I be able to write a code to keep words in separate entries, and turn numbers inside the string into integers in the list? I am a beginner to programming who is currently learning Python in parallel with C.

  • 2
    If you Google the phrases "Python split string" and "Python check number", you’ll find tutorials that can explain it much better than we can in an answer here. – Prune Nov 08 '18 at 00:10
  • 3
    Possible duplicate of [How to split a string into a list?](https://stackoverflow.com/questions/743806/how-to-split-a-string-into-a-list) – Sufiyan Ghori Nov 08 '18 at 00:11
  • You need to use `split` to divide the string into four "words", then use the various string type checking methods (e.g. `isdigit`) to detect which are numbers. Then you can convert as needed. – Prune Nov 08 '18 at 00:11

2 Answers2

2

Look into the .split() function.

It takes the form of

str.split(sep=None, maxsplit=-1)

so you want your code to look like this to break it apart.

string1 = 'Twenty 20 Twelve 12'
string1.split()
#['Twenty', '20', 'Twelve', '12']

To convert the numbers to integers, just check for .isdigit()

[int(i) if i.isdigit() else i for i in string1.split()]
#['Twenty', 20, 'Twelve', 12]

if you're not familiar with list comprehensions, this is analogous to

values = []
for i in string1.split():
    if i.isdigit():
        values.append(int(i))
    else:
        values.append(i)

values
#['Twenty', 20, 'Twelve', 12]
Cohan
  • 4,384
  • 2
  • 22
  • 40
0

You really should google it....

but you can use split

string1 = 'Twenty 20 Twelve 12'
list1=string1.split(' ')
SuperStew
  • 2,857
  • 2
  • 15
  • 27