Python Classroom Series – 02/Mar/2020

Strings in Python

  • sequence of characters of unicode.
  • Python doesnt have a type character
  • Python characters arranged in a sequence
x = "Hello Python!"
x[0] => H
len(x) => 12
x[0:4] => Hell
type(x[0])  => string

Interpolation of String

  • Refer Here for PEP-0498
  • fstring:
    • use {<variable_name>} in single or double quotes
    • eg:
    name = 'QT'
    course = 'python
    print(f"{name} {course}")
    
  • % formatting:
    • eg:
    name = 'QT'
    course = 'python
    print("%s %s", %(name, course))
    
  • str.format:
    • eg:
    name = 'QT'
    course = 'python
    print('{} {}'.format(name,course))
    
    
    

Exercise: Write a python program to print the following

The current number is 1
The current number is 2
...
...
...
The current number is 100

  • Solution using fstring:
for number in range(1,100):
    print(f'The current number is {number}')

Important items to understand in strings

  • Python Escape Sequences
  • Messages consisting of single or double quotes or both:
    • Python Escape Sequence (”)
    message = "i don\'t want anything"
    different_way = " i don't want anything"
    
  • Windows Paths:
    • Use raw string or Escape Sequence
    my_home_dir = r'C:\users\qt'
    my_home_dir = 'C:\\users\\qt'
    

For online debugging

Fibonnaci Series

* [Refer Here](https://projecteuler.net/problem=2)
# assign number1 and number2
number1 = 1
number2 = 2
print(number1)
print(number2)
result = 0
sum = 2
while result < 100:  # 5,8 8 , true
 	result = number1 + number2 # 5,8,13
	if result < 100: # false
		print(result) # 8
		if result%2 == 0:
		    sum += result
	else:
		break
	number1 = number2 # 5
	number2 = result  # 8
print('sum of even valued terms below 100 is {}'.format(sum))

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About continuous learner

devops & cloud enthusiastic learner