Friday 14 April 2023

Program For String

 # This program demonstrates various string operations


# Define a string variable

my_string = "Hello, World!"


# Print the string

print("Original string: " + my_string)


# Get the length of the string

print("Length of string: " + str(len(my_string)))


# Convert the string to uppercase

print("Uppercase string: " + my_string.upper())


# Convert the string to lowercase

print("Lowercase string: " + my_string.lower())


# Replace a substring within the string

new_string = my_string.replace("World", "Python")

print("Replaced string: " + new_string)


# Check if the string starts with a specific substring

if my_string.startswith("Hello"):

    print("The string starts with 'Hello'")

else:

    print("The string does not start with 'Hello'")


# Check if the string ends with a specific substring

if my_string.endswith("World!"):

    print("The string ends with 'World!'")

else:

    print("The string does not end with 'World!'")


# Split the string into a list of words

word_list = my_string.split()

print("List of words in string: ")

for word in word_list:

    print(word)


# Join a list of strings into a single string

joined_string = " ".join(word_list)

print("Joined string: " + joined_string)


# Access individual characters in the string

print("First character: " + my_string[0])

print("Last character: " + my_string[-1])


# Slice a substring from the string

substring = my_string[0:5]

print("Substring: " + substring)


No comments:

Post a Comment

Program For String

 # This program demonstrates various string operations # Define a string variable my_string = "Hello, World!" # Print the string p...