A string is a sequence of characters and a list is a
sequence of values, but a list of characters is not the same as a string. To
convert from a string to a list of characters, you can use list:
>>>
s = 'spam'
>>>
t = list(s)
>>>
print t
['s',
'p', 'a', 'm']
>>>
type(s)
>>>
type(t)
List is the name of a built-in function, you should
avoid using it as a variable name. The function of list method is to break
string into individual letters. If you want to break string into words, you can
use the split method:
>>>
s = 'Say hello to my litte friend'
>>>
t = s.split()
>>>
print t
['Say',
'hello', 'to', 'my', 'litte', 'friend']
>>>print
t[2]
Hello
Once
you have used split to break the string into a list of tokens you can use the
index operator to look at a particular word in the list. You can also split the
words from string which are ‘connected’ using the ‘_’ or ‘-‘ character (or any
other character). First thing you need to specify what character you want to
remove from a string and store it as a variable and then pass it as an argument
to split method.
>>>
s = 'Say-hello-to-my-litte-friend'
>>>
rem = '-'
>>>
t = s.split(rem)
>>>
t
['Say',
'hello', 'to', 'my', 'litte', 'friend']
Opposite
to split method Python has join method. This method takes a list of strings and
concatenates the elements.
>>> t
['Say', 'hello', 'to', 'my', 'litte', 'friend']
>>> ad = ' '
>>> ad.join(t)
'Say hello to my litte friend'
In
this case the delimiter is a space character, so join puts a space between
words. To concatenate strings without spaces, use the empty string as adding
attribute.
>>> t
['Say', 'hello', 'to', 'my', 'litte', 'friend']
>>> ad = ''
>>> ad.join(t)
'Sayhellotomylittefriend'
No comments:
Post a Comment