-6

How do I split this string into a list of entities:

String=('Sues Badge', '£1.70', '3', '13')

I know that this string may look like a list already, but the program see it as a string. I have tried String.split(",","") however this did not work.

Desired Output

List= [Sues Badge,£1.70,3,13]

MainStreet
  • 129
  • 1
  • 1
  • 6
  • 3
    Your `String` is a tuple, so doesn't have a `split` function - try `list(String)` – Andrew Dec 17 '18 at 13:56
  • 2
    "I know that this string may look like a list already, but the program see it as a string" => what you posted actually looks like a tuple, so what make you say that "the program sees it as a string" ? – bruno desthuilliers Dec 17 '18 at 14:08

2 Answers2

1

First of all, this is neither a string nor a list, but a tuple, as indicated by the round brackets. split is a method of the str class, so it can't be used here. To convert a tuple t into a list, simply do

list_1 = list(t)
Flob
  • 898
  • 1
  • 5
  • 14
  • This doesn't output `[Sues Badge,£1.70,3,13]`. – CodeIt Dec 17 '18 at 14:20
  • I took the "split this string into a list of entities" as more important than the literal output the OP mentioned in his question, which is missing the quotes around the first list item, because they want to have a list and not something that looks like a list, but is really a string. – Flob Dec 17 '18 at 14:24
  • Maybe i got it wrong. I had included an alternate way to the one suggested in your answer. – CodeIt Dec 17 '18 at 14:25
  • 1
    which is also entirely correct, if you just look at the desired output. We just focused on different parts of the question that didn't go together :-) – Flob Dec 17 '18 at 14:26
0

As per my understanding the OP just want to see output as [Sues Badge,£1.70,3,13]. If i'm right, then the below code will help.

Try this:

string = ('Sues Badge', '£1.70', '3', '13') # a tuple
str1 = ",".join(string) # converting tuple into a string
str1 = '[' + str1 + ']' # adds opening and closing square brackets to match your desired output.
print(str1) 

Output:

[Sues Badge,£1.70,3,13]

If you were looking for an answer like this one. I have an alternative way. Check this:

string = ('Sues Badge', '£1.70', '3', '13') # a tuple
str1 = ",".join(string).split(',') # converting tuple into a string
print(str1) 

Output:

['Sues Badge', '£1.70', '3', '13'] 
CodeIt
  • 3,492
  • 3
  • 26
  • 37