May 30, 2024
"This is a string"
'single word'
'''This is a string'''
lecture2.py
file:
string1 = "This is a string"
string2 = 'single word'
string3 = '''This is a string'''
string = "This is Amit's book"
Ensures no confusion by the interpreter.\n
, tabs \t
)string = "This is a string\nWe are creating it in Python"
print(string)
Output:
This is a string
We are creating it in Python
+
operatorstring1 = "Amit"
string2 = "College"
final_string = string1 + " " + string2
print(final_string) # Output: "Amit College"
len()
to find string lengthlength = len(string1)
print(length) # Output: 4
[index]
string = "Python"
print(string[0]) # Output: 'P'
print(string[1]) # Output: 'y'
-1
print(string[-1]) # Output: 'n'
print(string[-2]) # Output: 'o'
[start:end]
part = string[1:4] # Output: 'yth'
start
index included, end
index excludedpart = string[:4] # Output: 'Pyth'
part = string[3:] # Output: 'hon'
endswith
: Checks if a string ends with certain characters
string.endswith("ing") # Output: True
capitalize
: Capitalizes the first character
string.capitalize()
replace
: Replaces old substring with new
string.replace("Python", "Java")
find
: Finds first occurrence of substring
string.find("thon") # Output: 2
count
: Counts occurrences of substring
string.count("a")
if
, elif
, else
if condition:
# Execute this block
elif other_condition:
# Execute this block
else:
# Execute this block
age = 21
if age >= 18:
print("Can vote and apply for license")
else:
print("Cannot vote")
light = "green"
if light == "red":
print("Stop")
elif light == "green":
print("Go")
else:
print("Look")
if
statement inside another if
age = 95
if age >= 18:
if age >= 80:
print("Cannot drive")
else:
print("Can drive")
else:
print("Cannot drive")
number = int(input("Enter a number: "))
if number % 2 == 0:
print("Even")
else:
print("Odd")
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))
if a >= b and a >= c:
print("First is largest")
elif b >= a and b >= c:
print("Second is largest")
else:
print("Third is largest")
number = int(input("Enter a number: "))
if number % 7 == 0:
print("Multiple of 7")
else:
print("Not a multiple of 7")