Search code examples
pythonechowc

Can someone explain why the outcome isn’t the same?


I’m learning bash and Python. So I try to solve most questions with both Bash and Python. That’s how I ended up with trying to get the length of a string in both Bash and Python, and wc is giving back a different number. Searched the internet to find an answer, but didn't find it.

$ echo "ensPpaJxUanRSxRzWSqMcLrYZDhkCp" | wc -c
      31
====
$ echo "ensPpaJxUanRSxRzWSqMcLrYZDhkCp" | wc -m
      31
====
$ string="ensPpaJxUanRSxRzWSqMcLrYZDhkCp"
$ echo ${#string}                          
30
====
>>> print(len("ensPpaJxUanRSxRzWSqMcLrYZDhkCp"))
30

Solution

  • echo produces a new-line which is counted as an additional character, as @khelwood comments:

    $ echo "ensPpaJxUanRSxRzWSqMcLrYZDhkCp" | python -c 'import sys; print(list(sys.stdin))' 
    ['ensPpaJxUanRSxRzWSqMcLrYZDhkCp\n']