Python Strings
- String in python is a sequential data type.
- It is a sequence of characters.
- String behaves in the same manner as the list does in python.
- Strings are mutable datatype you can update, insert, delete string after defining it.
- String in python is defined inside Quotes("Codersdaily").
- Characters inside the string can be accessed by their index values.
a="codersdaily"
print(a)
print(a[0])
print(a[2])
Output -
codersdaily
c
d
Python is a versatile programming language that comes with a wide range of built-in string methods. These methods can be used to manipulate, format, and process strings in various ways. Here are some of the most commonly used Python string methods along with examples:
capitalize()
: This method returns a string with the first character capitalized and the rest of the characters in lowercase.string = "hello world" new_string = string.capitalize() print(new_string) # Output: "Hello world"
upper()
: This method returns a string with all characters in uppercase.string = "hello world" new_string = string.upper() print(new_string) # Output: "HELLO WORLD"
lower()
: This method returns a string with all characters in lowercase.string = "HELLO WORLD" new_string = string.lower() print(new_string) # Output: "hello world"
strip()
: This method returns a string with leading and trailing whitespace removed.string = " hello world " new_string = string.strip() print(new_string) # Output: "hello world"
split()
: This method splits a string into a list of substrings based on a specified delimiter.string = "apple,banana,orange" new_list = string.split(",") print(new_list) # Output: ["apple", "banana", "orange"]
join()
: This method joins a list of strings into a single string using a specified delimiter.list_of_strings = ["apple", "banana", "orange"] new_string = ",".join(list_of_strings) print(new_string) # Output: "apple,banana,orange"
replace()
: This method replaces all occurrences of a specified substring with another substring.string = "hello world" new_string = string.replace("world", "python") print(new_string) # Output: "hello python"
startswith()
: This method returns True if a string starts with a specified substring, and False otherwise.string = "hello world" result = string.startswith("hello") print(result) # Output: True
endswith()
: This method returns True if a string ends with a specified substring, and False otherwise.string = "hello world" result = string.endswith("world") print(result) # Output: True
find()
: This method returns the index of the first occurrence of a specified substring in a string, or -1 if the substring is not found.string = "hello world" index = string.find("world") print(index) # Output: 6