Strings continued
-
Getting a Substring with Slice:
- We can extract a substring (part of a string) from a string using a slice
- We can define slice by using square brackets
- start offset
- end offset
- step count
- syntax:
my_text = 'Hello How are you?' mytext[start_offset:end_offset:step]
- Examples: 1
- Examples: 2
- Create a letters variable
letters = "abcdefghijklmnopqrstuvwxyz"
- Now print all the letters from m to z
letters[12:]
- Now try to print alternative letters from a to z i.e. ace…..
letters[::2]
- Now print all the letters in reverse
letters[::-1]
- Print letters from e to l
letters[4:12]
- Print letters from s to w
letters[18:23] letters[18:-3]
- Print every third character from d to y
letters[3:25:3] letters[3:-2:3]
-
Length function
len()
counts the characters in string
len(letters)
-
Substitute by Using replace()
-
Strip with strip():
-
swapcase() function:
-
Miscellaneous functions of string:
Program:
- Write a program in Python to find all the even numbers from 100 to 1000
- When to want to execute any lines of code repetitively then we need to use the looping constructs.
- The first looping construct is while
- Repeat with while:
while <condition>:
<block>
- As long as condition is true the block of while executes
- Refer Here
Project Euler 1:
- Refer Here for the problem description
- Refer Here for the code done in the class.
Project Euler 6:
- Refer Here for the problem description
- Refer Here for the code created
- Fix for this problem is to increment index Refer Here