Python String into array

Posted under » JavaScript » Python on 25 July 2022

Just like PHP explode, Javascript too can make string into array

In javascript

taik = 'https://www.colorzilla.com/gradient-editor/--url color';
pecah = taik.split("--");
storage = pecah[0];

Meanwhile in Python

txt = "Hi, My name is LKY, and I love you"
x = txt.split(", ")
print(x)

Setting the maxsplit parameter to 1, will return a list with 2 elements!

x = txt.split(", ", 1)

If there is no delimiter, you can split each char including spaces by

list("Hi, My name is LKY, and I love you")

To see the array,

print (x[0])
print (x[1])
print (x[2])

You can use split to get integers in the string

status = 'LKY is no 1 PM'
pm_no = int(status.split(' ')[3])

Where the [#] is the number of spaces delimited.

Sometimes you don't have a way to split. So we have to `slice' the string which is similar to PHP substring.

txt = 'LKYinHell'
print(txt[1:5])

There may be sometime you want to store array data into a string field in MySQL. eg. which is something lazy programmers do.

[ 2172, 2174, 2175, 2173 ]

To process this, you need to treat it like a JSON and convert it to array. You can do this by converting this to array

import json
taikstring = '[ 2172, 2174, 2175, 2173 ]'
json_object = json.loads(taikstring)
print(json_object[2])
2175

For Concate string.

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data