Python provides a rich set of operations and methods to work with strings, which are sequences of characters enclosed in either single quotes (‘ ‘) or double quotes (” “).
Here are some common operations and methods you can perform on strings in Python:
- String Creation: You can create a string by assigning a value to a variable using quotes:python
my_string = 'Hello, World!'
String Concatenation: You can concatenate two or more strings using the
string1 = 'Hello' string2 = 'World' result = string1 + ' ' + string2 # 'Hello World'
String Length: To determine the length of a string, you can use the
my_string = 'Hello, World!' length = len(my_string) # 13
Accessing Characters: You can access individual characters in a string using indexing:
my_string = 'Hello, World!' first_char = my_string # 'H' last_char = my_string[-1] # '!'
String Slicing: Slicing allows you to extract a portion of a string by specifying start and end indices:
my_string = 'Hello, World!' sub_string = my_string[7:12] # 'World'
String Methods: Python provides various built-in methods to manipulate strings. Here are a few examples:
my_string = ' Hello, World! ' stripped_string = my_string.strip() # 'Hello, World!' uppercase_string = my_string.upper() # ' HELLO, WORLD! ' lowercase_string = my_string.lower() # ' hello, world! ' replaced_string = my_string.replace('o', 'e') # ' Helle, Werld! '
These are just a few examples of what you can do with strings in Python. Python’s string handling capabilities are quite extensive, and you can explore more methods and operations in the official Python documentation.