Sunday, May 17, 2020

Strings: creation and methods

Strings


To define a string variable either use double quotes or pair of single quotes but don't mix them.


filename = "GoTribe"

fname = 'yes man'


You can do a multi-line string assignment just like a multi-line comment using triple quotes; the triple quotes can be either single or double.


essay = """ write

stuff

here """


reply = '''

anything

you

want

'''


Python does not have a character type so in Python the character is a string of length 1.


String indexing starts at 0 and is accessed using a pair of []. If you optionally use the slice function, which is denoted by a colon :, inside the square brackets a range of indices is permitted. In the range the rightmost one will be excluded but the leftmost index in the range will be included. You can also do negative indexing where you start from the back of the string and move forward to the left of the string using a pair of negative numbers. If for some reason you write code or mistype your index so that you have positive and negative indices, then a print function won't fail but it will return empty or maybe an unexpected result.


apple = "fruit"

apple[0] = "f"

apple[0:0] = "f"

apple[4] = "t"

apple[0:1] = "f"

apple[0:5] = "frui"

# note you can over step the string boundary without error

apple[0:6] = "fruit"

apple[-85:-1] = "fruit"

apple[-4:-1] = "rui"


# notice how Python handles mixed sign indices

# it grabs the right most index and starts processing from there!


apple = "fruit"

apple[2:-1] = "ui" # start at -1 which is i then move 2 from front inclusive is u

apple[-2:5] = "it" # start at 5 which is one position out of bounds, then move 2                                         # units to the right inclusive from that position!

apple[-2:-5] = "" # start at -5 which is out of bounds on the right

                                # most side, then move -2 from t = [0], which is like putting the

                                # cart before the horse. There is no overlap so Python returns                                       # an empty string.



It's useful to distinguish between a Python function, which is a part of the python interpreter available to all code sections, versus a python method which belongs to a particular class. In this blog I will put functions in bold green font face and methods in black italics.



The built-in functions in and not in are interesting; they tell you if a certain substring is (or is not) a member of a larger string. For the purposes of using in and not in, all strings have the empty string (a pair of double quotes with nothing in between)


Functions

get a string's length: len()

check if a string exists in another string: in


Methods

d = "anc"

d.upper() # gives ANC

d. replace("c", "t") # gives ant


Python permits you to combine string literals with string variables using the plus sign


a = "strategy"


merged = "exit" + a # is valid


The String format method allows you to insert strings into a larger target string using placeholders and where one or more arguments have a definitive order to them starting at index 0. Just because you pass in any number of arguments to the format method called doesn't mean you have to use them all. In fact you can use any or none of them out of sequence. However, if you decide to start manually putting indices into the place holders then you have to do it for all of them. In other words you can't leave some place holders blank and some place holders with an index; you'll get an error that reads something like "cannot switch from Auto to manual specification".


people = 3
SKU = 567
sale_price = 49.95
account = "{} people want item {} for {} dollars."
print(account.format(people, SKU, sale_price))


python>> 3 people want item 567 for 49.95 dollars # same result people = 3 SKU = 567 sale_price = 49.95 account = "{0} people want item {1} for {2} dollars." print(account.format(people, SKU, sale_price)) python>> 3 people want item 567 for 49.95 dollars # argument 1 is not used, but script still works people = 3 SKU = 567 sale_price = 49.95 account = "{0} people want item for {2} dollars." print(account.format(people, SKU, sale_price)) python>> 3 people want item for 49.95 dollars people = 3 SKU = 567 sale_price = 49.95 account = "{0} people want {} item for {2} dollars." print(account.format(people, SKU, sale_price)) # you can not use empty braces and assigned braces in the same format call. python>> ValueError: cannot switch from manual field specification to automatic field numbering If you want to include a " inside a string you have to escape it with the backslash \. Interesting to note that if you use a ' within a pair of double quotes that does not need to be escaped. If escape characters are unwieldy or inconvenient you can just concatenate using the plus sign + and maintain all your double quotes.



Note that some string methods such as upper and lower do not take arguments.









No comments:

Post a Comment