dfeich / org-babel-examples

Examples using emacs org mode babel inline source code with different backend languages
570 stars 116 forks source link

Help, How to preserve leading zeros of table cells when using orgtable_to_dataframe #5

Closed yssource closed 5 years ago

yssource commented 5 years ago

I know this is a problem about org-mode table, instead of orgtable-to-dataframe. But, I'd like to get help from you. Thanks.

There are string-type numbers in 'id' column originally, but it is always interpreted as numbers by org-babel. I wonder how keep those leading zeros in org-babel?

demo

id name age
0001 Apollo 16
0002 Bmw 16
#+name: TBL
|   id | name   | age |
|------|--------|-----|
| 0001 | Apollo |  16 |
| 0002 | Bmw    |  16 |

#+BEGIN_SRC python :results output :var tbl=TBL
  print(tbl)
#+END_SRC
#+RESULTS:
: [[1, 'Apollo', 16], [2, 'Bmw', 16]]
dfeich commented 5 years ago

Hi

This is indeed a problem of the org-babel code that translates the table into the source block. You can expand the source block with org-babel-expand-src-block to see how the variable is passed over in the code.

This results in this:

tbl=[[1, "Apollo", 16], [2, "Bmw", 16]]
print(tbl)

The only slightly ugly workaround (besides changing the babel source) is to put the numbers in the ID column in quotes.

Cheers, Derek

yssource commented 5 years ago

Thanks. I find a way to solve my problem. Though It's not the proper place opening the issue here, maybe It will help others who have the same problem.

#+BEGIN_SRC emacs-lisp
  (defun my/org-babel--string-to-number (string)
    "If STRING represents a number return its value.
  Otherwise return nil."
    (and (string-match-p "\\`-?\\([1-9]\\|[0-9]*\\.\\)[0-9]*\\'" string)
         (string-to-number string)))

  (advice-add 'org-babel--string-to-number :override 'my/org-babel--string-to-number)

  ;; test
  (mapcar (lambda (string)
            (and (my/org-babel--string-to-number string)
                 t))
          '("001" "0.1" "00.1" "100" "100.1"))
  ;; => (nil t t t t)
#+END_SRC

#+RESULTS:
| nil | t | t | t | t |