Strings are defined using single (' '
) or double (" "
) quotes and are of type str
. For multi-line text, triple quotes (''' '''
or """ """
) can be used.
Strings are immutable, meaning their contents cannot be changed after creation.
my_str = "Python"
print(type(my_str)) # Output: <class 'str'>
len()
to count characters.*
to repeat strings.+
to join strings.
text = "Python"
print(text[0]) # Output: 'P'
print(text[1:4]) # Output: 'yth'
print(len(text)) # Output: 6
print(text * 2) # Output: 'PythonPython'
print(text + " Rocks!") # Output: 'Python Rocks!'
Method | Description |
---|---|
str.lower() | Converts all characters to lowercase |
str.upper() | Converts all characters to uppercase |
str.strip() | Removes whitespace or specified characters from both ends |
str.replace(old, new) | Replaces occurrences of a substring |
str.find(sub) | Finds index of first occurrence of a substring |
str.split(delimiter) | Splits string into list based on delimiter |
str.join(list) | Joins list elements into a string using a separator |
str.startswith(prefix) | Checks if string starts with specified prefix |
str.endswith(suffix) | Checks if string ends with specified suffix |
str.isdigit() | Returns True if string contains only digits |
text = " Python is Fun! "
print(text.strip()) # Removes leading/trailing spaces
print(text.lower()) # Converts to lowercase
print(text.find("is")) # Output: 9
print(text.replace("Fun", "Powerful")) # Replaces substring
print(text.split()) # Output: ['Python', 'is', 'Fun!']
print("-".join(["A", "B", "C"])) # Output: 'A-B-C'
print(text.startswith("Py")) # False due to leading spaces
print("123".isdigit()) # Output: True
Strings in Python are versatile and essential for text-based operations. From slicing and joining to formatting and condition checks, mastering string manipulation helps you write clean, expressive, and efficient Python code.