Working with Strings

Strings Basic

Strings are immutable (meaning you can’t use indexing to change individual elements of a string).


Slicing

Allows you to grab a subsection of multiple characters.
Syntax: [start:stop:step]
Start – numerical index for the slice start
Stop – numerical index for the slice stop (but not included)
Step – size of the jump you take


Concatenation Using Slicing

Strings can be saved into variables. The single quote is not included on the value of the variables a and b from the example below.


String Formatting has 2 methods:

.format() – inserts the string into a string where the curly braces are placed. For multiple entries, strings are inserted on the same order as they were supplied inside .format() if the {} are empty

Single element:

print('this is {}'.format('INSERTED'))
this is INSERTED

Multiple elements:

print('this is {}{}{}'.format('1','2','3'))
this is 123

Multiple elements
For multiple entries, where {} are not empty, it follows the index of strings inside .format(). The strings inside .format can be re-used as well.):

print('this is {2}{3}{1}{3}{0}'.format('1st','2nd','3rd',' --*-- '))
this is 3rd --*-- 2nd --*-- 1st

Assigning keywords to .format strings

print('DISPLAY: {a}{b}{c}'.format(a='aaa',b='bbb',c='ccc'))
DISPLAY: aaabbbccc

Float Formatting (f-strings)
Float formatting follows “{value:width.precision f}”
Width is just the white space / allowance given to the decimal point.
Precision is the number of decimal places returned.

By default, a division resulting to a non-whole number will return an answer with multiple decimal places:

result=100/777
print(result)
0.1287001287001287

By using float formatting:

print('RESULT = {r:1.3f}'.format(r=result))
RESULT = 0.129

Another method of Inserting Strings
This is introduced in Python 3. The f-strings allows the insert to be done more straightforward. It’s common on other programming languages.

name='Putsoy'
print(f'Hello, {name}')
Hello, Putsoy

Example for multiple variables:

name='Putsoy'
attribute='gwapo'
age=4
print(f'Si {name} ay {age} na, ay {attribute} pa :P Suya?')
Si Putsoy ay 4 na, ay gwapo pa :P Suya?

Formatting with Placeholders
%s can also be used to inject strings into print statements.

Example for injecting single item:

print("Si %s ay gwapo." %'Puchu')
Si Puchu ay gwapo.

Example for injecting multiple items:

print("Si %s ay %s at %s, pero %s." %('Puchu','gwapo','matalino','mataba'))
Si Puchu ay gwapo at matalino, pero mataba.

Example for injecting multiple items using variable names:

a,b,c,d='Puchu','gwapo','matalino','mataba'
print("Si %s ay %s at %s, pero %s." %(a,b,c,d))
Si Puchu ay gwapo at matalino, pero mataba.

Format Conversion Methods
%s – converts any Python object into a string using the str() method. It does not process escape characters and converts everything (including integers and floats) into purely string.
%r – converts any Python object into a string using the repr() method. The repr() method delivers the string representation of the object, including the quotation mark and any escape character.
%d – converts the number s into integers first without rounding. In other words, it only obtains the whole part of a number. Example, 4.06 = 4.

%s Examples:

#Command:
print('You make my blood %s.' %'boils')
#Output:
You make my blood boils.

#Command (including escape character):
print('You make my blood %s.' %'\tboils')
#Output:
You make my blood 	boils.

#Command (passing a float):
print('Puchu weighs %skgs.' %8.68)
#Output:
Puchu weighs 8.68kgs.

%r examples:

#Command:
print('You make my blood %r.' %'boils')
#Output:
You make my blood 'boils'.

#Command (including escape character):
print('You make my blood %r.' %'\tboils')
#Output:
You make my blood '\tboils'.

%d Example:

#Command (passing a float):
print('Puchu weighs %dkgs.' %8.68)
#Output:
Puchu weighs 8kgs.

Multiple Formatting

#Command:
print('%s is still %r even if he weighs %dkgs' %('Puchu','handsome',8.68))
#Output:
Puchu is still 'handsome' even if he weighs 8kgs

Strings and Operators

Using the + operator allows concatenation of strings or variables that contain strings.

Concatenation of strings

Concatenation of variables containing strings

The * operator allows replication of a string.


Getting Characters from Strings Using Indexes

Indexes starts with 0 (zero).

From the example below, notice that the very first letter from the string is returned when you call the a[0]:

Indexing can also be used directly with strings:

Indexes can be stored into variables and processed by expressions:


Negative Indexes

Negative indexes starts at the end of a string and go backwards. The negative index -1 is the index of the last character of the string.

From the example below, P is the first character of the string, which is the index 0 or index -18, while L is the last character which is the index 17 or index -1.


Slices

A slice is basically an index which contains 2 indexes separated by a colon [a:b]. It simply means it will get the characters from index a to the character before index b.

The example below shows the result slice 5:9. It tries to obtain the 6th character (which is equivalent to index 5) up to the 10th character (which is equivalent to index of 9). The result can also be stored into a variable and processed by an operator.

The result of a slice can also be processed by an index or another slice.

Slices will not give any error if the numbers are incorrect. It will only return the widest matching slice it can.

Blank Slices
If you omit the first number, it will return all the characters before the second index given. If you omit the second index, it will return all the characters starting the first index given. In this example, the 11th index is the space.


print() Function
Print allows displaying a string, a number, a variable containing a string, a result of an expression, and a lot more. One main difference of a regular output compared to print() is that the single quote is not included.


Printing Escape Characters

Escape Characters
\\ – Backslash (\)
\’ – Single Quote (‘)
\” – Double Quote (“)
\n – New Line
\t – Tab

Escape characters will not work by simply having them output into the shell:

You will need yo use the print() function for them to work.


Quotes and Double Quotes

Basically, there is not much difference when using a single or a double quote when displaying or storing a string.

However, to be able to use a double quote without using an escape character, you may use a single quote. Notice the difference below: