November 20th, 2012, 05:18 AM
2 newbie questions; input and string manipulations
im new to python and i can really use some help with it.
my first question:
is there a simple way to obtain as input three integers from user with one command?
im talking about something equivalent to the c command where you can obtain as many inputs as you want with just one line:
my second question:
scanf("%d %d %d %d...", &a, &b, &c, &d...)
where can i find a list of functions that can manipulate strings?
for example, lets say im getting from the user an integer number (with raw_input) - and i want to access one of the memory cells (i assume python saves each digit on 4 bits memory cell) and change its value as i please.
or - another example - i want to count how many digits are there.
or - i want to evaluate if the string doesn't hold any signs(char), in other words - to make sure it holds only digits.
are these operations possible?
thanks in advanced, and have a nice day!
November 20th, 2012, 08:30 AM
First, it's not very pretty but:
Originally Posted by so.very.tired
>>> a,b,c=map(int,raw_input("enter three numbers separated by commas: ").split(','))
enter three numbers separated by commas: 12,24,42
see:5.6.1 String Methods ¶
November 20th, 2012, 08:43 AM
I'm not aware of a direct replacement for scanf in python but if you know what the separate is going to be, you can split the input by the separator and the eval it.
As an example to get a list of all numbers entered seperated by a space:
If you are using Python 3.x use input() instead of raw_input. You can use int() or float() etc instead of eval to get all numbers of the same type. This will throw an exception if invalid input is entered.
numlist = [eval(x) for x in raw_input().split(' ')]
The online python documentation contains all the standard methods for string manipulation. Don't worry about how the string is internally represented, just use the methods given.
Remember that a string is immutable (read-only) so you can access each character with  but not change it. You can also loop through the string with for.
As an example this will count the number of digits in an easy to understand way:
A more experienced Pythoner would use filter and lamda. Or you could use a regular expression (see the re module).
count = 0
digits = '0123456789'
for char in raw_input():
if char in digits:
November 20th, 2012, 02:13 PM
that was very helpful!