-3

I have a 2-element list like:

[(2, u'0.267*"sugar" + 0.266*"bad"'), (0, u'0.222*"father" + 0.222*"likes"')]

I want to get the first words of tuples that is I want to get a 2-element list as:

["sugar","father"]

I don't know how can I achive this since I am unfamilier with u' notation. Can anyone help or give some hints?

  • 1
    [Meaning of 'u' symbol in front of string values](https://stackoverflow.com/questions/11279331/what-does-the-u-symbol-mean-in-front-of-string-values) – metatoaster May 31 '18 at 12:51
  • 1
    This means the unicode string. – betontalpfa May 31 '18 at 12:51
  • 2
    the `u` prefix only means it's a (python 2.x) unicode string. They work just like bytestrings (ordinary python 2.x strings) wrt/ string manipulation operations, so just treat them as strings. – bruno desthuilliers May 31 '18 at 12:54

2 Answers2

1

Using str methods

Ex:

d = [(2, u'0.267*"sugar" + 0.266*"bad"'), (0, u'0.222*"father" + 0.222*"likes"')]
print([i[1].split("+")[0].split("*")[1].replace('"', "").strip() for i in d])

Output:

[u'sugar', u'father']
  • str.split to split string by ("+" and "*")
  • str.replace to replace extra quotes
  • str.strip to remove all trailing or leading space.
Rakesh
  • 81,458
  • 17
  • 76
  • 113
0

You can find the value of an index location using square brackets.

myList[index]

In nested lists:

myList[indexInOuterList][indexInInnerList]

For your situation:

myList[indexInList][indexInTuple]

mylist = [(2, u'0.267*"sugar" + 0.266*"bad"'), (0, u'0.222*"father" + 0.222*"likes"')]
myList[0][0] #This is the integer 2
Ctrl S
  • 1,053
  • 12
  • 31