How to manipulate /output integers/strings in Python

Hi all,

I’ve taken the plunge, and started to try Python. My first small task was to get a script to read the speed of an object and output it to a property. I found and adapted one from the archives, but also thought it would be nice to have an automatic kph/mph string on the end of the speed readout. I have tried using str() but I get ‘xspeed kph’ rather than ‘123 kph’- here is what I have so far:

import GameLogic

controller = GameLogic.getCurrentController()
object = controller.owner

Xspeed, Yspeed, Zspeed = object.getLinearVelocity(False)

linSum = Xspeed 

xValue = linSum

object['speed'] = xValue

kph = object['text2']

object['text'] = str("xValue" + "kph")

Where am I going wrong? I often get errors relating to str and int not mixing but I thought the str() command outputs what you send to it.

Thanks for your time!


object[‘text’] = str(xValue) +“kph”

I cant believe it was that simple, I feel a bit of an idiot!

I’m a bit confused as to what is going on though- am I isolating the integer from the string (so Python knows they are different types rather than making them all strings)?

shouldn’t it be:
object[‘text’] = str(xValue) + str(kph)
assuming you want to set the words “kph” from a property.
Of course that method works fine if not.

Both ways work well, but I have a minor problem-the velocity is now being read in a float style value (like 5.0032434234kph rather than 5kph). How would I change that to an integer (i.e whole numbers)?


python.blend (481 KB)

Use the int() function. For example:

object['text'] = str(int(xValue)) +"kph" 						

should also be able to do

object['text'] = int(xValue),"kph"

Cool, thanks for those suggestions SolarLune and Siegel!

By the way SolarLune, when is the next part of your Python tutorial series out? 2.5 series tutorials are like gold dust!

D’oh, I’ve gotta get on it. Since today’s Saturday, I’ll probably upload another today. Glad to know someone’s reading them!

Like I said, 2.5 tutorials are quite rare- and its really good having every line explained in detail in a game context. As a suggestion, it may be useful to have a small tutorial on converting old 2.49b scripts to 2.5x (or cover the basics). Either that or have a vault of useful mall scripts that people can pick apart.