Python 3x Pandas Django

Strings are Arrays

Strings are arrays of bytes representing Unicode characters

Strigs are ordered and sequence of characters

A single character is simply a string with a length of 1

x = "A"
print(x[1])

Output: A

x = "ASTRING"
print(x[1])

Output: A

Either you can create a string using single quotes or double quotes

user_name = "Michael"     #Output:Michael
user_name = 'Michael'     #Output:Michael

For Multiple line String use three single quotes '''

user_name = '''
Michael
Jackson
William'''

String Concatenation

first_name = "Sachin"
last_name  = "Tendulkar"
full_name  = first_name + " " + last_name    #Output: Sachin Tendulkar

Slicing

You can display a range of characters by using the slice syntax.

Syntax: array[start_index:end_index:step]

start_index included and end_index excluded when slicing

Illustrated in below diagram

Python Slicing

Syntax

  x ="ASTRING"
  #Slice from start_index '0' to '1' (end_index '2' excluded)
  print(x[:2])
  #Slice from start_index '0' to '-3' (end_index '-2' excluded)
  print(x[:-2])
  #Slice from start_index '2' to last available index
  print(x[2:])
  #Slice from start_index '-3' to last availabe index
  print(x[-3:])
  #Slice from start_index '0' to 1 (end_index '2' excluded)
  print(x[0:2])
  #Slice from start_index '-3' to '-3' (end_index '-2' excluded)
  print(x[-3:-2])
  #Slice from start_index 1 and end_index 4 ( 5 excluded) & with the step 2
  print(x[1:5:2])
  #Slice from start_index -1 and end_index -6 ( -5 excluded) & with the step 2
  print(x[-1:-5:-2])
  #Slice from start_index -1 to last available index with a step 0
  print(x[::-1])
  #Slice from start_index -1 to last available index with a step 0
  print(x[-1::-1])
  #above statement is equalvent to
  print(x[::-1])

Run code snippet

Immutability

Strings in python are immutable that means they can be changed

first_name = "Sachin"
first_name = "Sachin Tandulkar"  # We can re-assign but, can't change the value
print(first_name)                #Output: Sachin Tandulkar

first_name[8] = "e"
print(first_name)

Output:

TypeError: 'str' object does not support item assignment

You will get an error. Why is that? because strings are immutable that is, we can't change value(characters in the strings) once it created.

Data Type Conversion and Data Type Casting

Converting the value of one data type (integer, string, float, etc.) to another data type is called type conversion.

Python has two types of type conversion.

  1. Implicit Type Conversion
  2. Explicit Type Conversion

Implicit Type Conversion

  • In the below example, we can see the data type of num_integer is an integer while the data type of num_float is a float.
  • Also, we can see the num_new has a float data type because python always converts smaller data types to larger data types to avoid the loss of data.
  num_integer = 123
  num_float = 1.23

  num_new = num_integer + num_float

  print("datatype of num_integer:",type(num_integer))
  print("datatype of num_float:",type(num_float))

  print("Value of num_new:",num_new)
  print("datatype of num_new:",type(num_new))

Run code snippet

Explicit Type Conversion

  • In below example, we converted num_string from string(higher) to integer(lower) type using int() function to perform the addition.
  • After converting num_string to an integer value, Python is able to add these two variables.
  • We got the num_sum value and data type to be an integer.
  num_integer = 123
  num_string = "456"

  print("Data type of num_integer:",type(num_integer))
  print("Data type of num_string before Type Casting:",type(num_string))

  num_str = int(num_string)
  print("Data type of num_str after Type Casting:",type(num_string))

  num_sum = num_integer + num_str

  print("Sum of num_integer and num_string:",num_sum)
  print("Data type of the sum:",type(num_sum))

Run code snippet

Escape Sequences

Escape sequences allow you to include special characters in strings. To do this, simply add a backslash (\) before the character you want to escape.

Assume,if you want to print Hey, what's up?

print('Hey, what's up?')

then you will get an error in the output because single quotes ' used in python for string creation.

print('Hey, what's up?')
                 ^
SyntaxError: invalid syntax

To fix this, just escape the apostrophe \ :

print('Hey, what\'s up?')

To add newlines to your string, use \n :

print("Multiline strings in python\ncan be created\nusing escape sequences.")

Output:

Multiline strings in python
can be created
using escape sequences.

To add backslash character in a string, add one more escape \ :

print("C:\\Users\\Python\\")

Output:

C:\Users\Python\

For more detail, Please refer python docs

Formatted String (f-Strings)

f-strings are string literals that have an f at the beginning and curly braces containing expressions that will be replaced with their values. The expressions are evaluated at runtime and then formatted using the __format__ protocol

Here are some of the ways f-strings can make your life easier.

Simple Syntax

name = "Eric"
age  = 74
print(f"Hello, {name}. You are {age}.")   #Output: 'Hello, Eric. You are 74.'
print(F"Hello, {name}. You are {age}.")   #Output: 'Hello, Eric. You are 74.'

Both f & F are valid to form a f-strings

Arbitrary Expressions

Because f-strings are evaluated at runtime, you can put any and all valid Python expressions in them.You could do something pretty straightforward, like this:

print(f"{10 + 20}")     #Output: 30

For more detail, please refer Formatted String Literals

If you have any doubts or queries related to this chapter, get them clarified from our Python Team experts on ibmmainframer Community!