String and Array Formatting and Manipulation
Python [conda root] v2.7

In [11]:
my_quotation_for_manipulation = "Do not go gentle into that good night.  Rage, rage against the dying of the light."
author = "Dylan Thomas"

def initialCaps_anyString(myString):    
    textList = myString.split(" ")
    myString = ""
    
    for i in range(len(textList)):
        textList[i] = textList[i].capitalize()
        myString = myString + textList[i] + ' '
        # i =+ 1
    
    # instead of if statemet to not add ' ' if last character, we simply remove it when done
    myString = myString[:-1]
    
    return myString

initial_caps_quotation = initialCaps_anyString(my_quotation_for_manipulation)
print("Initial Caps Version - my quotation string:\n     '%s'" %(initial_caps_quotation))

# notes from StackOverflow when earlier cut of this code was not working:
#   Len won't yield the total number of objects in a nested list (including multidimensional lists).
#   but len() will tell you the elements in string after you split it
#   If you have numpy, use size(). Otherwise use list comprehensions within recursion.


Initial Caps Version - my quotation string:
     'Do Not Go Gentle Into That Good Night.  Rage, Rage Against The Dying Of The Light.'

In [12]:
# this does same thing as above function:
initial_caps_quotation.title()


Out[12]:
'Do Not Go Gentle Into That Good Night.  Rage, Rage Against The Dying Of The Light.'

In [2]:
job_title_string = "ASSISTANT DIRECTOR - SOLUTION SPECIALIST"
print(initialCaps_anyString(job_title_string))


Assistant Director - Solution Specialist

In [33]:
# print "Some text {:g2} more text {0}" .format(myvariable1, mybariable2)
# numers just set order on passing variables in and optional if you write code in sequence
# :2g = formatter for floating point and 2 would set number of decimals
# but look at these examples below ... (tried f on a lark by things seen somewhere else)

myVariable1 = "Something"
myVariable2 = "Stupid"
myNumber = 748.43987612543
myOtherNumber = 7.43987612543

print "Say {} very {}".format(myVariable1, myVariable2)
print "Say {0} very {1}".format(myVariable1, myVariable2)
print "Say {1} very {0}".format(myVariable1, myVariable2)
print "Say {} very {} that costs ${:2g} of my time.".format(myVariable1, myVariable2, myNumber)
print "Say {} very {} that costs ${:2g} of my time.".format(myVariable1, myVariable2, myOtherNumber)
print "Say {} very {} that costs ${:2f} of my time.".format(myVariable1, myVariable2, myOtherNumber)


Say Something very Stupid
Say Something very Stupid
Say Stupid very Something
Say Something very Stupid that costs $748.44 of my time.
Say Something very Stupid that costs $7.43988 of my time.
Say Something very Stupid that costs $7.439876 of my time.

In [34]:
# continuing with above variables
# References:
#             https://pyformat.info/
#             http://stackoverflow.com/questions/1742937/convert-float-to-string-with-cutting-zero-decimals-afer-point-in-python

print " .3f:  Say {} very {} that costs ${:.3f} of my time.".format(myVariable1, myVariable2, myOtherNumber)
print " .2f:  Say {} very {} that costs ${:.2f} of my time.".format(myVariable1, myVariable2, myOtherNumber)
print " .2g:  Say {} very {} that costs ${:.2g} of my time.".format(myVariable1, myVariable2, myOtherNumber)
print "  2f:  Say {} very {} that costs ${:2f} of my time.".format(myVariable1, myVariable2, myOtherNumber)
print "  2g:  Say {} very {} that costs ${:2g} of my time.".format(myVariable1, myVariable2, myOtherNumber)
print "    :  Say {} very {} that costs ${} of my time.".format(myVariable1, myVariable2, myOtherNumber)


 .3f:  Say Something very Stupid that costs $7.440 of my time.
 .2f:  Say Something very Stupid that costs $7.44 of my time.
 .2g:  Say Something very Stupid that costs $7.4 of my time.
  2f:  Say Something very Stupid that costs $7.439876 of my time.
  2g:  Say Something very Stupid that costs $7.43988 of my time.
    :  Say Something very Stupid that costs $7.43987612543 of my time.

In [35]:
# source: https://learnpythonthehardway.org/book/ex5.html
# something to try:  %r should print anything no matter what? (at least in Python 2.7)
xNum = 415
yNum = -8.143

print "Warning:  Use of \%r returns 'raw' version of the content.  \nThis is not always a good thing."
print "Test of percent r: %r" % ("something stupid")
print "Test of percent r: %r" % (xNum)
print "Test of percent r: %r" % (yNum)

print "\nWorking With The Approximate number %d" % (yNum)
print "Working With The Exact number %s" % str(yNum)
print "Rounding The Number {:.3f}".format(yNum)
print round(yNum)
print round(yNum, 2)


Warning:  Use of \%r returns 'raw' version of the content.  
This is not always a good thing.
Test of percent r: 'something stupid'
Test of percent r: 415
Test of percent r: -8.143

Working With The Approximate number -8
Working With The Exact number -8.143
Rounding The Number -8.143
-8.0
-8.14

In [26]:
# comma on end of print statement keeps it from outputting the \n
print "my content ...",
print "more of my content\n"

someVariable = 777

# \ continues on next line when it is the last character for the line
# otherwise, this is the escape character

print '''\
Going to attempt a multi-line print statement but pass in a numeric variable.
This print statement uses the multi-line syntax combined with percent-d to get this variable: %d''' % someVariable


my content ... more of my content

Going to attempt a multi-line print statement but pass in a numeric variable.
This print statement uses the multi-line syntax combined with percent-d to get this variable: 777

In [14]:
mySimpleArray = [1, 3, 45, 100, 1200, 798]
mySimpleArray[0]


Out[14]:
1

In [15]:
# 1 upto index 3 - so only returns 2 elements
mySimpleArray[1:3]


Out[15]:
[3, 45]

In [16]:
# slices from 1 to the end (skip index zero)
print(mySimpleArray)
print("   %s" %mySimpleArray[1:])


[1, 3, 45, 100, 1200, 798]
   [3, 45, 100, 1200, 798]

In [19]:
# slices from the last character to the end (which is just one character in this case)
print(mySimpleArray)
print((" "*20 + " %s") %mySimpleArray[-1:])


[1, 3, 45, 100, 1200, 798]
                     [798]

In [24]:
# moving backwardsthrough the array
print(mySimpleArray)
print((" "*22 + "%s") %mySimpleArray[-1])
print((" "*15 + "%s") %mySimpleArray[-3:-1])
print((" "*10 + "%s") %mySimpleArray[-3:])


[1, 3, 45, 100, 1200, 798]
                      798
               [100, 1200]
          [100, 1200, 798]

In [10]:
# this is Python 2.7 sytax only.  In Python 3, the command is input()

yourname = raw_input('Enter your name (input): ')
print(yourname)


Enter your name (input): Mitch was here
Mitch was here

In [26]:
# tupple versus list syntax - if second line is commented out, that means error was thrown and tupple was confirmed

# list:
seq = ["a", "b", "c"]
seq[0] = "b"

# tupple
seq2 = ("a", "b", "c")
# seq2[0] = "b"        # throws error / can't modify tuple

# tupple
seq3 = "a", "b", "c"
# seq3[0] = "b"
# seq3.pop           # throws error / can't modify tuple

print("seq: %s" %seq)
print("seq2: (%s, %s, %s)" %seq2)  # note: see related sample cells that follow this one
print("seq3: (%s, %s, %s)" %seq3) 

print("-----------------------")
print("seq before .pop():")
print(seq)
seq.pop()
print("seq after .pop():")
print(seq)
print("more changes to seq:")
seq = ["a"] + seq + ["c", "d", "e", "f"]
seq.append("h")      # appends one value at a time (pass in list and it becomes sublist)
print(seq)
print(".pop(2) from seq:")
seq.pop(2)
print(seq)


seq: ['b', 'b', 'c']
seq2: (a, b, c)
seq3: (a, b, c)
-----------------------
seq before .pop():
['b', 'b', 'c']
seq after .pop():
['b', 'b']
more changes to seq:
['a', 'b', 'b', 'c', 'd', 'e', 'f', 'h']
.pop(2) from seq:
['a', 'b', 'c', 'd', 'e', 'f', 'h']

In [17]:
# note how this is stored / output
# and yet - it required the different approach to printing in previous cell or it threw an error
seq2


Out[17]:
('a', 'b', 'c')

In [27]:
# same as previous example
seq3


Out[27]:
('a', 'b', 'c')

In [31]:
# workaround:
print("seq3: %s" %[seq3])


seq3: [('a', 'b', 'c')]

In [32]:
myStr = "here is some text."
print myStr.upper()


HERE IS SOME TEXT.

In [33]:
from __future__ import print_function
# in python file - this must come first!  but in Jupyter/iPython we can get away with this
# this line does nothing in Python 3.x, it is used in Python 2.7 to make print work like Python 3.x

print("something stupid")
print("... and something even more stupid")
print("")

print("something stupid", end="")
print("... and something even more stupid")
print("")

# note:  cannot use sep and end in same code.  But this illustrates sep better:
# Not supported:  
#    print("something", "stupid", "and", "...", "something", "even", "more", "stupid %s", sep="_") % ("than that")
print("something", "stupid", "and", "...", "something", "even", "more", "stupid", sep="_")

# basic print test:
print("%s %s %s %d times." % ("say", "something", "stupid", 3))

# combining concepts:
print("something", "stupid", "and", "...", "something", "even", "more", "stupid %s times %d!" % ("than that", 3), sep="_")

# copied from code file that used i in it - stderr example:
# i value dummied up to show this test:

from sys import stderr
i = 10
print("Arg %d does not exist." %(i), file=stderr)
print("Warning: Arg %d" %(i), "does", "not", "exist.", file=stderr, sep="_")


something stupid
... and something even more stupid

something stupid... and something even more stupid

something_stupid_and_..._something_even_more_stupid
say something stupid 3 times.
something_stupid_and_..._something_even_more_stupid than that times 3!
Arg 10 does not exist.
Warning: Arg 10_does_not_exist.

In [35]:
# random code -- try / catch which in Python is try / exception example
# allows scanning an array without knowing its length

myArray = [1 , 2, 3, 4]

def get_value_from_array(myArray, indxToGet):
     try:
          return myArray[indxToGet]
     except IndexError:
          print("Warning: Index %d does not exist." %(i), file=stderr)
          return False
        
print(get_value_from_array(myArray, 2))
print(get_value_from_array(myArray, 12))


3
False
Warning: Index 10 does not exist.

In [37]:
url = "C:\\Users\\Mitch\\Documents\\Code\\Git_Repo"
# Help for this function
# https://www.tutorialspoint.com/python/string_replace.htm
# sample code: str.replace(old, new[, max])

def convert_win_path_to_onlinePath(inputURL):
    return inputURL.replace("\\", "/")

print("Test with escaped path passed in from variable:")
print(convert_win_path_to_onlinePath(url))
print()


Test with escaped path passed in from variable:
C:/Users/Mitch/Documents/Code/Git_Repo


In [39]:
print(convert_win_path_to_onlinePath(raw_input('input() File Path to Convert here:\n')))


input() File Path to Convert here:
d:\some path\with folders\and more folders\
d:/some path/with folders/and more folders/

In [40]:
# from Big Data Class
# only works if this command is the only thing in the cell
# adding comments to the cell triggers error ... even ws triggers an error
# best threory:  command must be only thing in the cell for it to work

# this lists variables and function declarations currently in use in the notebook

In [41]:
who


convert_win_path_to_onlinePath	 get_value_from_array	 i	 myArray	 myStr	 print_function	 seq	 seq2	 seq3	 
stderr	 url	 

In [42]:
print("here is some content ...",
      "here is some more content")


here is some content ... here is some more content

In [55]:
print("Some float using percent-d: %d" %(3.9415678))
print("Some float using percent-i: %i" %(3.9415678))


Some float using percent-d: 3
Some float using percent-i: 3

In [43]:
print()




In [44]:
myTestList = [1,2,3]
print(type(myTestList))
if str(type(myTestList)) == "<class 'list'>":
    print("This is a list")
else:
    print("I don't know what that is.")

myTestStr = "some text."
print(type(myTestStr))


<type 'list'>
I don't know what that is.
<type 'str'>

In [45]:
# (start, end, increment)
# [start:end:increment]

lst = range(2,10,2)
print(lst)
print(lst[0:2])
print(lst[2:])        # index 2 to the end
print(lst[-1:-3:-1])  # count back from the end incrementing by 1 so 8, then 6 then stop since end is not inclusive


[2, 4, 6, 8]
[2, 4]
[6, 8]
[8, 6]

In [46]:
lst[3]


Out[46]:
8

In [9]:
strTest = "Something Stupid"
# we can flip it with slice ::-1 => start defaults to first index value, end defaults to include last element, increment by -1
strTest[::-1]


Out[9]:
'diputS gnihtemoS'

In [ ]: