Strings in Python

To create a string variable, enclose characters with " " or ' ' 

Example:

string1 = "This is Python string 1"

string2 = 'This is Python string 2'

print(string1)

print(string2)


#output: 

This is Python string 1

This is Python string 2


This is when defining strings on a single line. There exists a possibility to define a string that spread on multiple lines using triple double quotes or triple single quotes i.e. """ or '''. 

Example: 

string_m = """Today is Monday and 

the sky is perfect clear"""


To understand the way to access elements in a string we start from analogy that Python strings are like a list of characters, hence elements can be accessed using index, negative index or even slicing notation. Exist also __getitem__() method which is a little bit similar with accessing using index. 


Example using index: 

mystr = "Today is Monday"

print(mystr[0]) 

print(mystr[1]) 


#output: 

T

o


Example using negative index:

mystr = "Today is Monday"

print(mystr[-1])

print(mystr[-3])


#output: 

Y

d

We observe that negativ index "count back" from the end of the string elements.


Example using slicing notation: 

mystr = "Today is Monday"

print(mystr[0:2]) 

print(mystr[1:5]) 


#output: 

To

oday

We observe that in slicing it count till "right slice value -1" means mystr[0:2] will show mystr[0], mystr[1] but will not show mystr[2]


Example using __getitem__()

mystr = "Today is Monday"

print(mystr.__getitem__(0))


#output

T


String comparison

It is performed with == operator

example: 

s1="alfa"

s2="Alfa"

s3="alfa"

if(s1==s2):

    print("s1 is equal with s2")

else:

    print("s1 is not equal with s2")

#

if(s1==s3):

    print("s1 is equal with s3")

else:

    print("s1 is not equal with s3")


#output: 

s1 is not equal with s2

s1 is equal with s3

We observe that == with strings is case sensitive.


The other way to compare strings is using __eq__() or __ne__()

Example: 

s1="alfa"

s2="Alfa"

s3="alfa"

print(s1.__eq__(s2))

print(s1.__eq__(s3))

print(s1.__ne__(s2))


#output:

False

True

True

Thus method __eq__() return True if strings are equal, while __ne__() return True if strings are not equal. Basically == operator automatically call __eq__() method.


Concatenating or joining strings

Strings can be concatenated using "+"  operator

Example: 

s1 = "Alfa"

s2 = "Beta"

print(s1+s2)


#output:

AlfaBeta

locals() and globals() in Python

Python globals() function

Method globals() return a dictionary which contains global environment variables used by interpretor for the program.

Example: 

print(globals())


#output

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000024C64E14850>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:\\Users\\Stefan\\builtin1\\main.py', '__cached__': None}



Or writing each key:value of dictionary in a single line, example:

d_globals = globals()

for key in d_globals.copy():

    print(f"{key}: {d_globals[key]}")

#output

__name__: __main__

__doc__: None

__package__: None

__loader__: <_frozen_importlib_external.SourceFileLoader object at 0x000001FFF0B44850>

__spec__: None

__annotations__: {}

__builtins__: <module 'builtins' (built-in)>

__file__: C:\Users\Stefan\builtin1\main.py

__cached__: None



Python locals() function

Method locals(), return a dictionary which contains all environment variables (key: value) related to program local scope. 

Example:

print(locals())


#output

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000001449C894850>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:\\Users\\Stefan\\builtin1\\main.py', '__cached__': None}


Or writing each key:value of dictionary in a single line, example:

d_locals = locals()

for key in d_locals.copy():

    print(f"{key}: {d_locals[key]}")


#output

__name__: __main__

__doc__: None

__package__: None

__loader__: <_frozen_importlib_external.SourceFileLoader object at 0x000001EFDCAF4850>

__spec__: None

__annotations__: {}

__builtins__: <module 'builtins' (built-in)>

__file__: C:\Users\Stefan\builtin1\main.py

__cached__: None


If we define a local variable in the program, it will appear in locals() output.

Example in below with variable named month:

def aboutyear():

    month = 'May'

    print(locals())

    print(locals()['month'])


print(aboutyear())


#output: 

{'month': 'May'}

May

We see in this case printing locals() inside function aboutyear will print only one key:value  for the variable month defined inside (or local) in the function itself.


We can change values for a key from locals() or globals(). Below is an example of doing this with a key from globals():

year=2023

def aboutmonth():

    month = 'May'


print(globals())

globals()['year']=2022

print(globals())


#output: 

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000023389FB4850>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:\\Users\\Stefan\\builtin1\\main.py', '__cached__': None, 'year': 2023, 'aboutmonth': <function aboutmonth at 0x0000023389EF3E20>}


{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000023389FB4850>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:\\Users\\Stefan\\builtin1\\main.py', '__cached__': None, 'year': 2022, 'aboutmonth': <function aboutmonth at 0x0000023389EF3E20>}


We see first print(globals()) will contain global variable year with value 2023, but it will not print local variable month which is inside function aboutmonth

Then we change global variable year to 2022 using globals()['year']=2022

Hence second print(globals()) will contain global variable year with value 2022