-3

When i just make a variable,i get this. please see below

a = 'a d c'
a
'a d c'
a.split()
['a', 'd', 'c']

When i make a function, i get this. please see below

def x():
    a = 'abc ash avs'
    a.split()
    print a

x()
abc ash avs
  • split() does not split in place, it returns a list: words = a.split() – Joucks Jul 20 '15 at 16:31
  • possible duplicate of [Split string into a list in Python](http://stackoverflow.com/questions/743806/split-string-into-a-list-in-python) – Joucks Jul 20 '15 at 16:31

3 Answers3

2

split() returns a list of the words in the string you pass it. You are not updating the variable a when calling it in your function.

def x():
    a = 'abc ash avs'
    a = a.split()
    print a
ILostMySpoon
  • 2,399
  • 2
  • 19
  • 25
0

You're not modifying the a string itself since Python strings are immutable. Because you're in the interpreter it will print what a function returns. That's why you get the list printed on screen there. But the x function doesn't return the split list, merely prints a.

You'll see your expected result if you switch to this:

def x():
    a = 'abc ash avs'
    print a.split()

And you can see what I mean about a not being modified with this:

a = 'a d c'
a
'a d c'
a.split()
['a', 'd', 'c']
a
'a d c'
SuperBiasedMan
  • 9,814
  • 10
  • 45
  • 73
0

The method split() split your string based on whitespace when you don't pass a specific argument to it. So in your function it split 'abc ash avs' based on spaces.

If you want the characters you can use list function.

>>> a = 'abc ash avs'
>>> list(a)
['a', 'b', 'c', ' ', 'a', 's', 'h', ' ', 'a', 'v', 's']

And if you want alphabetical characters you can use a list comprehension to get them :

>>> [i for i in a if i.isalpha()]
['a', 'b', 'c', 'a', 's', 'h', 'a', 'v', 's']
Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • So python knows the alphabet like it can "sort" numbers? – corb shum Jul 20 '15 at 16:24
  • @corbshum Sorry I didn't get you can you explain more! – Mazdak Jul 20 '15 at 16:25
  • @corbshum Python does know how to sort letters alphabetically, but I think you misunderstood that part of the answer. Kasramvd was showing you how to make a list of the characters that are letters (ie. Alphabetical) while leaving out spaces. It seems like Kasra thought you wanted a list of every letter, not a list split by spaces. – SuperBiasedMan Jul 20 '15 at 16:28
  • Sorry i did miss read it and deleted the comment ha not quick enough though! I learned something new though and it makes sense so thank you for your time and helo – corb shum Jul 20 '15 at 16:30
  • @SuperBiasedMan Good explain but already I said that for getting a list of all letters OP can use `list()` function! – Mazdak Jul 20 '15 at 16:32
  • @corbshum Its OK, welcome. fortunately SuperBiasedMan added some explain! – Mazdak Jul 20 '15 at 16:33