Practical -String Functions
Practical -String Functions
String Functions
1. capitalize()-
str1="hello python"
>>> str1.capitalize()
'Hello python'
>>> str1
'hello python'
>>> str2=str1.capitalize()
>>> str2
'Hello python'
>>>
2. center()
str1.center(30)
' hello python '
3. count() -counts the no of occurrences of a particular in the string
>>> subject="Python Programming"
>>> subject.count("r")
2
4. find()
• The find() method finds the first occurrence of the specified value.
• The find() method is almost the same as the index() method, the
only difference is that the index() method raises an exception if the
value is not found.
subject="Python Programming"
subject.find("on")
>>> subject.find("no")
-1
5. index()
subject="Python Programming"
subject.index("on")
4
>>> subject.index("no")
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
subject.index("no")
ValueError: substring not found
5. replace()
The replace() method replaces a specified phrase with another
specified phrase.
Syntax: string.replace(oldvalue, newvalue, count)
Parameter Description
Count Optional. A number specifying how many occurrences of the old value you
want to replace. Default is all occurrences
subject.replace("Python","Java")
'Java Programming'
6. split()
Split a string as per separator into a list where each word is a list item
You can specify the separator, default separator is any whitespace.
string.split(separator, maxsplit)
Parameter Description
str="abc,def,ghi,jkl"
>>> str.split(",")
['abc', 'def', 'ghi', 'jkl']
7. join()
• The join() method takes all items in an iterable and joins them
into one string.
list1=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday"
,"Saturday"]
>>> str1="#".join(list1)
>>> str1
'Sunday#Monday#Tuesday#Wednesday#Thursday#Friday#Saturday'
8. strip()
The strip() method removes any leading (spaces at the beginning)
and trailing (spaces at the end) characters (space is the default leading
character to remove)
str1=" abc "
>>> str1=str1.strip()
>>> str1
'abc'
9. upper()- Converts a string into upper case
10.lower()-Converts a string into lower case
11.title()-Converts a string into title case
12. isalnum()
Returns True if all characters in the string are alphanumeric
13. isalpha()
Returns True if all characters in the string are in the alphabet
14. isdecimal()
Returns True if all characters in the string are decimals
15. isdigit()
Returns True if all characters in the string are digits
16. isidentifier()
Returns True if the string is an identifier
17. islower()
Returns True if all characters in the string are lower case
18. isnumeric()
Returns True if all characters in the string are numeric
19. isprintable()
Returns True if all characters in the string are printable
20. isspace()
Returns True if all characters in the string are whitespaces
21. istitle()
Returns True if the string follows the rules of a title
22. isupper()
Returns True if all characters in the string are upper case