What is String in Python?
- A string in Python is a sequence of characters, like letters, numbers, and symbols, enclosed in quotes.
- Strings are used to represent text.
Example:
# Single quote string single_quote_string = 'Hello, World!' # Double quote string double_quote_string = "Python programming is easy." # Multi-line string multi_line_string = """This is a string that extends across multiple lines.""" # Printing the strings print(single_quote_string )
print(double_quote_string )
print(multi_line_string)
Output:
Hello, World! Python programming is easy. This is a string that extends across multiple lines.
Basic String Operations and Methods in Python:
Concatenation:
- Combining two or more strings into one.
Example:
str1 = "Hello" str2 = "World" result = str1 + " " + str2 print(result) # Output: Hello World
Repetition:
- Repeating a string multiple times.
Example:
str1 = "Python! " result = str1 * 3 print(result) # Output: Python! Python! Python!
Indexing:
- Accessing individual characters in a string using their index (starting from 0).
Example:
str1 = "Python" print(str1[0]) # Output: P print(str1[1]) # Output: y print(str1[-1]) # Output: n (last character)
Slicing:
- Slicing extracts a portion of a string by specifying a range of indices.
Example:
str1 = "Python Programming"
# Extracting a substring from index 0 to 5 (not including 6)
print(str1[0:6]) # Output: Python
# Extracting a substring from index 7 to the end
print(str1[7:]) # Output: Programming
# Extracting every second character from the entire string
print(str1[::2]) # Output: Pto rgamn
# Extracting a substring from index -11 to -1 (not including -1)
print(str1[-11:-1]) # Output: Programming
# Reversing the string
print(str1[::-1]) # Output: gnimmargorP nohtyP
.upper() Method:
- Converts all characters in a string to uppercase.
Example:
str1 = "hello" result = str1.upper() print(result) # Output: HELLO
.lower() Method:
- Converts all characters in a string to lowercase.
Example:
str1 = "HELLO" result = str1.lower() print(result) # Output: hello
.replace() Method:
- Replaces occurrences of a substring with another substring.
Example:
str1 = "Hello World" result = str1.replace("World", "Python") print(result) # Output: Hello Python
.split() Method:
- Splits a string into a list of substrings based on a delimiter.
Example:
str1 = "Python is simple" result = str1.split(" ") print(result) # Output: ['Python', 'is', 'simple']
0 Comments