I need to know if i can take a user inputed string such as

``name = raw_input("Enter Name:")``

and take the word inputed and break the string apart by letters for example:
If the user enters "joe"
i will get "j", "o", "e"
is this possible?
also i need to know if i can take a line like this:

``print (1+2+3+4+5+6)``

and take the resulting number "21" and get two numbers "2" and "1" so i can add those to finally output "3". Thanks in advance

4
Contributors
5
Replies
6
Views
7 Years
Discussion Span
Last Post by pyTony

Yes, both can be done. You would use a for() loop to traverse the strings, or convert to a list, in both cases.

Edited by woooee: n/a

I would generate numbers with divmod to built in sum function.

So would i save the output in the second example as a variable and then work with it?

Some pratice you can try out in IDLE.

``````>>> name = raw_input("Enter Name: ")
Enter Name: joe
>>> name
'joe'
>>> list(name)
['j', 'o', 'e']

>>> #This is called list comprehension
>>> [i for i in name]
['j', 'o', 'e']

>>> #Written as an ordenarry loop
>>> my_list = []
>>> for i in name:
my_list.append(i)
>>> my_list
['j', 'o', 'e']

#one with map()
>>> map(str, name)
['j', 'o', 'e']

>>> #convert to string
>>> ''.join(my_list)
'joe'

>>> n = (1+2+3+4+5+6)
>>> n
21

>>> l = list(str(n))
>>> l
['2', '1']

#list comprehension
>>> [i for i in l]
['2', '1']
>>> [int(i) for i in l]
[2, 1]
>>> sum([int(i) for i in l])
3
>>>``````

From generator like here sum of numbers 0...9:

``````>>> sum(number for number in xrange(10))
45``````

I would write my function and replace the xrange(10) with numbers_of_the(number) which would loop and use yield to return the values.