String operations are operations that you can perform on strings in Python. Here are some of the most common string operations:
len(string): Returns the length of the string.string.upper(): Returns a copy of the string with all characters in uppercase.string.lower(): Returns a copy of the string with all characters in lowercase.string.strip(): Returns a copy of the string with all leading and trailing whitespace removed.string.replace(old, new): Returns a copy of the string with all occurrences of old replaced by new.string.split(): Returns a list of the words in the string, using whitespace as the delimiter.string.join(list): Returns a string that is the concatenation of the strings in list, separated by string.string.startswith(prefix): Returns True if the string starts with prefix, False otherwise.string.endswith(suffix): Returns True if the string ends with suffix, False otherwise.string.find(substring): Returns the index of the first occurrence of substring in the string, or -1 if substring is not found.Here are some examples of using these string operations:
string = " Hello, world! "print(len(string)) # Output: 18print(string.upper()) # Output: " HELLO, WORLD! "print(string.lower()) # Output: " hello, world! "print(string.strip()) # Output: "Hello, world!"print(string.replace("o", "X")) # Output: " HellX, wXrld! "print(string.split()) # Output: ["Hello,", "world!"]words = ["Hello", "world", "!"]print("-".join(words)) # Output: "Hello-world-!"print(string.startswith(" ")) # Output: Trueprint(string.endswith("! ")) # Output: True
|
In these examples, we define a string string and use various string operations to manipulate it. We use the len() function to determine the length of the string, and the upper() and lower() methods to change the case of the string. We also use the strip() method to remove leading and trailing whitespace, the replace() method to replace characters in the string, and the split() method to split the string into a list of words. Finally, we use the join() method to concatenate a list of strings, and the startswith(), endswith(), and find() methods to search for substrings in the string.