In Python, strings are sequences of characters, represented within either single quotes ' ', double quotes " ", or triple quotes ''' ''' or """ """.
Strings are immutable, meaning once they are created, they cannot be changed.
Here are some common operations and functionalities related to strings in Python:
We can create strings using single quotes, double quotes, or triple quotes for multi-line strings.
string1 = 'Hello' string2 = "World" multilineString = '''This is a multi-line string'''
We can concatenate strings using the "+" operator.
full_string = string1 + ' ' + string2
We can find the length of a string using the "len()" function.
string1 = "Hello" string2 = "World" string1Length = len(string1) // 5 string2Length = len(string2) // 5 multiLineStringLength = len(multilineString) // 27
We can access individual characters or substrings within a string using indexing and slicing.
string1 = "Hello" string2 = "World" char = string1[0] // Output: 'H' substring = string2[1:3] // Output: 'or'
Python provides a variety of built-in methods for working with strings, such as "upper()", "lower()", "strip()", "split()", "join()", "replace()", "find()", and many more.
str = 'This is a single-line string!!''' print(str.upper()) // Output: THIS IS A SINGLE-LINE STRING!! print(str.lower()) // Output: this is a single-line string!! print(str.strip("!!")) // Output: this is a single-line string print(str.split()) // Output: ['This', 'is', 'a', 'single-line', 'string!!'] print("-".join(str)) // Output: T-h-i-s- -i-s- -a- -s-i-n-g-l-e---l-i-n-e- -s-t-r-i-n-g-!-! print(str.replace("single-line", "line")) // Output: This is a line string!! print(str.find("single-line")) // Output: 10
Python provides methods to check String starting and ending with substring using "startswith()", "endswith()".
str = 'This is a single-line string!!''' print(str.startswith("This")) // Output: True print(str.endswith("!@")) // Output: False
Python provides a method to convert a list into a string using "join()".
# Using List your_list = ["apple", "banana", "orange"] print(",".join(your_list)) // Output: "apple, banana, orange"
We can format strings using the "%" operator ("printf-style formatting"), "str.format()" method, or "f-strings" (formatted string literals).
formatted_string = 'Hello, %s!' % 'World' formatted_string = 'Hello, {}!'.format('World') formatted_string = f'Hello, {"World"}!'
We can create raw strings using the "r" or "R" prefix, which treats backslashes "\" as literal characters.
raw_string = r'C:\Users\Alice'
We can include special characters in strings using escape sequences, such as "\n" for newline, "\t" for tab, "\\" for a backslash, \" for a double quote, and \' for a single quote.
escaped_string = 'This is a new line.\nThis is a tab:\tHello'