A string is a sequence of characters enclosed within single quotes (' '), double quotes (" "), or triple quotes (''' ''' or """ """).
Example
name = "Python"
message = 'Hello World'
String Slicing
Slicing is used to extract a portion of a string.
Syntax
string[start:end:step]
Example
text = "Python Programming"
print(text[0:6]) # Python
print(text[7:18]) # Programming
print(text[:6]) # Python
print(text[::2]) # Pto rgamn
print(text[::-1]) # gnimmargorP nohtyP
Features
- Start index is inclusive.
- End index is exclusive.
- Negative indexing is allowed.
- Step value controls the interval.
Membership Operators in Strings
Membership operators check whether a character or substring exists in a string.
Operators
innot in
Example
text = "Python"
print("Py" in text) # True
print("Java" in text) # False
print("Java" not in text) # True
Uses
- Searching substrings.
- Validation of user input.
- Checking existence of characters.
Built in String Functions
1. count()
Returns the number of occurrences of a substring.
Syntax
string.count(substring)
Example
text = "banana"
print(text.count("a"))
Output
3
2. find()
Returns the index of the first occurrence of a substring.
Syntax
string.find(substring)
text = "Python Programming"
print(text.find("Pro"))
7
-1.3. capitalize()
Converts the first character into uppercase and remaining characters into lowercase.
Example
text = "python programming"
print(text.capitalize())
Python programming
4. title()
Converts the first letter of each word into uppercase.
Example
text = "python programming language"
print(text.title())
Python Programming Language
5. lower()
Converts all characters to lowercase.
Example
text = "PYTHON"
print(text.lower())
python
6. upper()
Converts all characters to uppercase.
Example
text = "python"
print(text.upper())
PYTHON
7. swapcase()
Converts uppercase letters to lowercase and lowercase letters to uppercase.
Example
text = "PyThOn"
print(text.swapcase())
pYtHoN
8. replace()
Replaces a specified substring with another substring.
Syntax
string.replace(old, new)
text = "I like Java"
print(text.replace("Java", "Python"))
I like Python
9. join()
Joins elements of an iterable into a single string.
Syntax
separator.join(iterable)
words = ["Python", "is", "easy"]
print(" ".join(words))
Python is easy
10. isspace()
Returns True if all characters are whitespace characters.
Example
text = " "
print(text.isspace())
True
11. isdigit()
Returns True if all characters are digits.
Example
text = "12345"
print(text.isdigit())
True
12. split()
Splits a string into a list.
Syntax
string.split(separator)
text = "Python,Java,C++"
print(text.split(","))
['Python', 'Java', 'C++']
13. startswith()
Checks whether a string starts with a specified value.
Example
text = "Python Programming"
print(text.startswith("Python"))
True
14. endswith()
Checks whether a string ends with a specified value.
Example
text = "Python Programming"
print(text.endswith("ming"))
True