Python Forum
Learning python specific syntax after using other scripting languages for years
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Learning python specific syntax after using other scripting languages for years
#4
Quote:why does it not convert things to be printable without converting types?

Unlike a lot of languages, Python doesn't let you add numbers to strings and vice versa. The following is simply not supported:

s = "Hello " + 5
I can't give you the Pythonic answer for this(i.e., why the designers chose not to support it). Personally, I don't like implicit casting and from my own experience, using a wide range of languages, I prefer it this way.

Instead Python supports string formatting.
https://docs.python.org/2/library/string.html
https://docs.python.org/2/library/functions.html#print

So here's your code:
print(str(k) + ":" + str(v) + "\n")
Which is creating a string by concatenating the various pieces and if 'k' or 'v' are integers, it won't work.

It can be done in two ways:
print("%s:%s"%(k, v))
print("{0}:{1}".format(k,v))
Personally, I find the latter easier to read. Note that I didn't include the '\n', that's included automatically, unless you specify something different with the end keyword argument.

You can also simply print integers without effort:
x = 5
print(x)
Reply


Messages In This Thread
RE: Learning python specific syntax after using other scripting languages for years - by mpd - Dec-11-2017, 12:46 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Converting days to years in loop while computing values across grid cells Lightning1800 2 2,682 May-15-2018, 08:44 PM
Last Post: Lightning1800

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020