1.
Write a Python program to calculate the length of a string using:
a) Length function
b) Any Loop (with comments)
# Using len() function
string = "Hello World"
print("Length using len():", len(string))
# Using loop
count = 0
for char in string:
count += 1
print("Length using loop:", count)
2. Write a Python program to get a string made of the first 2 and last 2 characters of a given
string. If the string length is less than 2, return an empty string ('').
string = "w3resource"
if len(string) >= 2:
result = string[:2] + string[-2:]
else:
result = ''
print("Result:", result)
3. Write a Python program to get a string from a given string where all occurrences of its first
char have been changed to '$', except the first char itself.
string = "google"
first_char = string[0]
modified = first_char + string[1:].replace(first_char, '$')
print("Modified string:", modified)
4. Write a Python program to remove characters that have odd index values in a given string.
string = "abcdef"
# Method 1: Slicing
print("Using slicing:", string[::2])
# Method 2: Loop
result = ''
for i in range(len(string)):
if i % 2 == 0:
result += string[i]
print("Using loop:", result)
5. Write a Python program to get a single string from two given strings, separated by a space
and swap the first two characters of each string.
str1 = "abc"
str2 = "xyz"
new_str1 = str2[:2] + str1[2:]
new_str2 = str1[:2] + str2[2:]
result = new_str1 + " " + new_str2
print("Resulting string:", result)
6. Write a Python script that takes input from the user and displays that input back in upper
and lower cases.
user_input = input("Enter a string: ")
print("Uppercase:", user_input.upper())
print("Lowercase:", user_input.lower())
7. Write a Python program to check whether a string starts with and ends with specified
characters. (Use assigned string 'w3resource.com')
string = "w3resource.com"
start_substring = "w3"
end_substring = ".com"
# Method 1: Using startswith and endswith
print("Starts with w3:", string.startswith(start_substring))
print("Ends with .com:", string.endswith(end_substring))
# Method 2: Using slicing
print("Using slicing:")
print("Starts with w3:", string[:len(start_substring)] == start_substring)
print("Ends with .com:", string[-len(end_substring):] == end_substring)
8. Write a Python program to format strings in different ways (min 2 ways). Input: Name =
Shyam, Age = 30
name = "Shyam"
age = 30
# Method 1: Using f-string
print(f"My name is {name} and I am {age} years old")
# Method 2: Using format() method
print("My name is {} and I am {} years old".format(name, age))