Python String Function
Here are some common Python string handling functions/methods with simple examples:
1. len() – Find string length
name = "Nilesh"
print(len(name))
Output: 6
2. upper() – Convert to uppercase
name = "nilesh"
print(name.upper())
Output: NILESH
3. lower() – Convert to lowercase
name = "NILESH"
print(name.lower())
Output: nilesh
4. strip() – Remove extra spaces
name = " Nilesh "
print(name.strip())
Output: Nilesh
5. replace() – Replace text
text = "I like Java"
print(text.replace("Java", "Python"))
Output: I like Python
6. split() – Split a string
text = "Python is easy"
print(text.split())
Output:
['Python', 'is', 'easy']
7. find() – Find position of text
text = "Python Programming"
print(text.find("Programming"))
Output: 7
8. count() – Count occurrences
text = "banana"
print(text.count("a"))
Output: 3
9. startswith() – Check beginning
text = "Python Programming"
print(text.startswith("Python"))
Output: True
10. endswith() – Check ending
text = "Python.py"
print(text.endswith(".py"))
Output: True
11. isalpha() – Check only alphabets
text = "Python"
print(text.isalpha())
Output: True
12. isdigit() – Check only numbers
text = "12345"
print(text.isdigit())
Output: True
Combined Example
name = " Python Programming "
print("Original:", name)
print("Length:", len(name))
print("Uppercase:", name.upper())
print("Lowercase:", name.lower())
print("Without spaces:", name.strip())
print("Replace:", name.replace("Python", "Java"))
print("Split:", name.split())
These are the most commonly used Python string handling functions/methods for beginners.
Comments
Post a Comment