Python String Programs Yash
Python String Programs Yash
a) Length function
# Using loop
count = 0
count += 1
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:
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]
string = "abcdef"
# Method 1: Slicing
# Method 2: Loop
result = ''
for i in range(len(string)):
if i % 2 == 0:
result += string[i]
5. Write a Python program to get a single string from two given strings, separated by a space
str1 = "abc"
str2 = "xyz"
6. Write a Python script that takes input from the user and displays that input back in upper
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"
print("Using slicing:")
8. Write a Python program to format strings in different ways (min 2 ways). Input: Name =
Shyam, Age = 30
name = "Shyam"
age = 30