Python String is the sequence of characters enclosed in either single (' '
), double (" "
), or triple (''' '''
or """ """
) quotes.
Creating Strings
Strings can be created using single, double, or triple quotes.
single_quoted_str = 'Hello, World!' double_quoted_str = "Python Programming" triple_quoted_str = '''This is a multi-line string in Python'''
Important: You can use triple quotes to create a string with multiple lines, character \n
is in triple_quoted_str
.
Example:
multi_line_string = ''' This is a string with multiple lines using triple quotes. ''' print("---start---") print(multi_line_string) print("---end---")
Output:
---start--- This is a string with multiple lines using triple quotes. ---end---
Concating String
Strings can be concatenated using the +
operator.
str1 = "Hello," str2 = " World!" concatenated_str = str1 + str2
Indexing String
Individual characters in a string can be accessed using index numbers (starting at 0).
my_str = "Python" char = my_str[0] # Accessing the first character 'P'
Slicing String
You can use the syntax [start:stop:step]
to extract substrings.
my_str = "Python Programming" substring = my_str[7:18] # Extracts "Programming"
Reversing String
You can use string slicing to reverse a string.
my_string = "Hello, World!" reversed_string = my_string[::-1] print(reversed_string) # Output: "!dlroW ,olleH"