1

I currently have a file that's being read and making every line into a list. The file looks like this:

A  11   1
B  12   2
C  11   2

It's easy to make a list using split()

['A', '11', '1']

But how do I make a list that contains both chars and ints such that I get this below:

['A', 11, 1]

would be grateful for some help!

Barmar
  • 741,623
  • 53
  • 500
  • 612
Eliz M.
  • 11
  • 1
  • There's probably some fancy way, but you could just use some for loops to test for ints and replace if needed – SuperStew Feb 16 '18 at 19:59
  • Also see: https://stackoverflow.com/questions/1265665/how-can-i-check-if-a-string-represents-an-int-without-using-try-except – ZaxR Feb 16 '18 at 20:05
  • Is it always ints in the same columns? – Barmar Feb 16 '18 at 20:12
  • ah thank you all for the help. this really warmed my heart to see a lot of constructive help; this is my first stackoverflow question and first python class. very grateful! – Eliz M. Feb 16 '18 at 20:23

1 Answers1

3

You can use the str.isdigit check as the conditional expression condition to get the digits to make ints:

[int(i) if i.isdigit() else i for i in line.split()]

As e.g. '-1'.isdigit() would returns False, we can use re to do string matching:

rcomp = re.compile(r'^[+-]?\d+$')
[int(i) if rcomp.search(i) else i for i in str_.split()]

e.g:

In [59]: str_ = 'A 2 3'

In [60]: [int(i) if i.isdigit() else i for i in str_.split()]
Out[60]: ['A', 2, 3]

In [61]: str_ = 'A -3 4 -8'

In [62]: [int(i) if rcomp.search(i) else i for i in str_.split()]
Out[62]: ['A', -3, 4, -8]
heemayl
  • 39,294
  • 7
  • 70
  • 76
  • `'-1'.isdigit()` is false, though. `isdigit` doesn't fit the "test whether a string represents a number" use case as well as people keep expecting it to. – user2357112 Feb 16 '18 at 20:14
  • @user2357112 True. Edited to include some string matching with `re` instead of `str.isdigit`. – heemayl Feb 16 '18 at 20:24
  • `i.strip('-').isdigit()` would also be an option to account for negative numbers. – Darkonaut Feb 16 '18 at 20:27