Thursday, October 9, 2014

Convert string to array in python

Example:
   string1 = 'It is so cold outside'
   array = string1.split(' ')

Check array:
   print array
   ['It', 'is', 'so', 'cold', 'outside']

Convert array to string:
   string2 = ' '.join(array)

Check string2:
   print string2
   'It is so cold outside'

Just for fun:
   string2 = '-'.join(array)

Check string2:
   print string2
   'It-is-so-cold-outside'

Wednesday, October 8, 2014

Covert string variable to array in bash script

The syntax is:
   array=($string)

Following is an example:
   string="where am I?"
   array=($string)

Check:
   for i in ${array[@]}; do echo $i; done
   where
   am
   I?

Convert array to string variable:
   for i in ${array[@]}; do abc="$abc `echo $i`"; done

Check:
   echo $abc
   where am I?

Additional array info:
   ${arr[*]} # All of the items in the array
   ${!arr[*]} # All of the indexes in the array
   ${#arr[*]} # Number of items in the array
   ${#arr[0]} # Length of item zero

Append new element to array:
   arr=(${arr[@]} element)
   arr+=(element)