# Define a sample string
sample_string = "Hello, World! This is a sample string."
# 1. Length of the string
print("1. Length of the string:", len(sample_string))
# 2. Convert the string to lowercase
print("2. Convert the string to lowercase:", sample_string.lower())
# 3. Convert the string to uppercase
print("3. Convert the string to uppercase:", sample_string.upper())
# 4. Count occurrences of a substring
substring = "is"
print("4. Count occurrences of '{}' in the string:".format(substring), sample_string.count(substring))
# 5. Check if the string starts with a specific prefix
prefix = "Hello"
print("5. Check if the string starts with '{}':".format(prefix), sample_string.startswith(prefix))
# 6. Check if the string ends with a specific suffix
suffix = "string."
print("6. Check if the string ends with '{}':".format(suffix), sample_string.endswith(suffix))
# 7. Find the index of a substring
substring = "World"
print("7. Find the index of '{}' in the string:".format(substring), sample_string.find(substring))
# 8. Replace occurrences of a substring with another substring
old_substring = "sample"
new_substring = "modified"
modified_string = sample_string.replace(old_substring, new_substring)
print("8. Replace occurrences of '{}' with '{}':".format(old_substring, new_substring), modified_string)
# 9. Split the string into a list of substrings based on a delimiter
delimiter = " "
split_string = sample_string.split(delimiter)
print("9. Split the string into substrings based on '{}':".format(delimiter), split_string)
# 10. Join a list of substrings into a single string using a delimiter
delimiter = "_"
joined_string = delimiter.join(split_string)
print("10. Join substrings into a single string using '{}':".format(delimiter), joined_string)
Output :
1. Length of the string: 382. Convert the string to lowercase: hello, world! this is a sample string.3. Convert the string to uppercase: HELLO, WORLD! THIS IS A SAMPLE STRING.4. Count occurrences of 'is' in the string: 25. Check if the string starts with 'Hello': True6. Check if the string ends with 'string.': True7. Find the index of 'World' in the string: 78. Replace occurrences of 'sample' with 'modified': Hello, World! This is a modified string.9. Split the string into substrings based on ' ': ['Hello,', 'World!', 'This', 'is', 'a', 'sample', 'string.']10. Join substrings into a single string using '_': Hello,_World!_This_is_a_sample_string.
No comments:
Post a Comment