Python String Methods


String Module

Before using the string module, we must import it.

>>> import string  
# returning all letters
>>> print(string.ascii_letters)
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

# returning all lowercase letters
>>> print( string.ascii_lowercase)
abcdefghijklmnopqrstuvwxyz

# returning all uppercase letters
>>> print(string.ascii_uppercase)
ABCDEFGHIJKLMNOPQRSTUVWXYZ

# returning white spaces
>>> print(string.whitespace)
 	

 

# retuning all digits
>>> print(string.digits)
0123456789

>>> if " " in string.whitespace:
	print(True)
	
True

>>> for i in string.whitespace:
	print( repr(i)) # repr convert special
                          character into normal
	
' '
'\t'
'\n'
'\r'
'\x0b'
'\x0c'

>>> print(string.punctuation)
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

                

String Methods

There are number of methods defined in Python to work with strings.

Some frequently used and important methods defined in Python 3 are listed below along with brief descriptions and examples.

1. capitalize() - Capitalizes first letter of string, rest will be in lower case.
>>> s = "hello world"
>>> s = s.capitalize()
>>> print(s)
Hello world
>>> s1 = "Python Prowess"
>>> s1 = s1.capitalize()
>>> print(s1)
Python prowess
>>> s1 = "PYTHON Prowess"
>>> s1 = s1.capitalize()
>>> print(s1)
Python prowess
>>>

2. title() - first character of each word capitalized, others lowercased
>>> s = "hello world"
>>> s = s.title()
>>> print(s)
Hello World
>>> s1 = "PYTHON Prowess"
>>> s1 = s1.title()
>>> print(s1)
Python Prowess
>>>

3. lower() - covert string to lower case

4. upper() - covert string to upper case

>>> s = "PYTHON Prowess"
>>> s = s.lower()
>>> print(s)
python prowess
>>> s = s.upper()
>>> print(s)
PYTHON PROWESS
>>>

5. islower() - checks whether all characters are lower case, returns True if all are in lower case else False.

6. isupper() - checks whether all characters are upper case, returns True if all are in upper case else False.

>>> s = "python prowess"
>>> if s.islower():
	print("all are in lower case")

all are in lower case
>>> s = "PYTHON PROWESS"
>>> if s.isupper():
	print("all are in upper case")

all are in upper case
>>>

7. isalpha() - Returns True, if string contains only alphabets else False.

8. isalnum() - Returns True, if string contains only alphabets,digits or both, else False.

9. isdigit() - Returns True, if string contains only digits else False.

>>> s = "prowess"
>>> print(s.isalpha())
True
>>> print(s.isalnum())
True
>>> print(s.isdigit())
False
>>> s = "prowess@123"
>>> print(s.isalpha())
False
>>> print(s.isalnum())
False
>>> print(s.isdigit())
False
>>> s = "prowess123"
>>> print(s.isalpha())
False
>>> print(s.isalnum())
True
>>> print(s.isdigit())
False
>>> s = "123"
>>> print(s.isalpha())
False
>>> print(s.isalnum())
True
>>> print(s.isdigit())
True
>>>

10. istitle() - Returns True, if only first letter of every word in string is capital, else False.

>>> s = "Python Prowess"
>>> print(s.istitle())
True
>>> s = "Python PRowess"
>>> print(s.istitle())
False
>>>

11. find(str, start, end) - returns the index of given str, if not found return -1.

12. index(str, start, end) - returns the index of given str, if not found return error.

If do not specify start and end in method, by deafault it takes start=0 and end=len(string)

>>> s = "Python Prowess"
>>> x = s.find("Py")
>>> print(x)
0
>>> x = s.find("t")
>>> print(x)
2
>>> x = s.find("z")
>>> print(x)
-1
>>> y = s.index("th")
>>> print(y)
2
>>> y = s.index("z")
Traceback (most recent call last):
  File "", line 1, in 
    y = s.index("z")
ValueError: substring not found
>>>

13. rfind(str, start, end) - returns the rightmost index of given str, if not found return -1.

14. rindex(str, start, end) - returns the rightmost index of given str, if not found return error.

>>> s = "Python Prowess"
>>> print(s.rfind('o'))
9
>>> print(s.rindex('P'))
7
>>> print(s.rfind('z'))
-1
>>> print(s.rindex('z'))
Traceback (most recent call last):
  File "", line 1, in 
    print(s.rindex('z'))
ValueError: substring not found
>>>

15. count(sub_str, start, end) - count number of occurrences of substring between start and end.

>>> s = "Python Prowess"
>>> c = s.count('P')
>>> print(c)
2
>>> c = s.count('P',0,6)
>>> print(c)
1
>>>

16. split(separator, max) -

The split() method splits a string into a list.

We can specify the separator, With no arguments, split() separates strings using one or more spaces as the delimiter.

If max is specified, then list will contain the specified number of elements plus one.
Default value of max is -1.

>>> s = "Welcome to Prowess Apps"
>>> x = s.split()
>>> print(x)
['Welcome', 'to', 'Prowess', 'Apps']

Use a hash character as a separator:
>>> s = "apple#banana#cherry#orange"
>>> x = s.split('#')
>>> print(x)
['apple', 'banana', 'cherry', 'orange']

>>> s = "Welcome to Python Prowess smarter way to learn Python"
>>> x = s.split(' ',4) # separator is space and max=4
>>> print(x)
['Welcome', 'to', 'Python', 'Prowess', 'smarter way to learn Python']
>>>

17. rsplit(separator, max) - r means right

The rsplit() method splits a string into a list, starting from right.

We can specify the separator, With no arguments, rsplit() separates strings using one or more spaces as the delimiter.

If max is not given, it returns the same result as split() method.

If max is specified, then list will contain the specified number of elements plus one.
Default value of max is -1.

>>> s = "Welcome to Prowess Apps"
>>> x = s.rsplit()
>>> print(x)
['Welcome', 'to', 'Prowess', 'Apps']

Use a hash character as a separator:
>>> s = "apple#banana#cherry#orange"
>>> x = s.rsplit('#')
>>> print(x)
['apple', 'banana', 'cherry', 'orange']

>>> s = "Welcome to Python Prowess smarter way to learn Python"
>>> x = s.rsplit(' ',5)
>>> print(x)
['Welcome to Python Prowess', 'smarter', 'way', 'to', 'learn', 'Python']
>>>

18. splitlines() - Lines of text can be separated with Windows, or UNIX, newline sequences. This makes splitting on lines complex. The splitlines () method helps here.

>>> s = """This string
has many
lines."""
>>> lines = s.splitlines()
>>> for line in lines:
	print("[" + line + "]")
	
[This string]
[has many]
[lines.]
>>>

19. join(iterable) - The join() method combines all the items of an iterable object into one string.

>>> list = ["a", "b", "c"]
#Join with empty string literal.
>>> result = "".join(list)
#Join with comma.
>>> result2 = ",".join(list)
#Display results
>>> print(result)
abc
>>> print(result2)
a,b,c

# tuple as iterable object to join
>>> myTuple = ("CProwess", "C++Prowess", "JavaProwess","PythonProwess")
>>> x = "#".join(myTuple)
>>> print(x)
CProwess#C++Prowess#JavaProwess#PythonProwess
>>>

20. strip(characters) -
The strip() method removes any leading and trailing characters.


21. lstrip(characters) -
The lstrip() method removes any character at the start of the string .


22. rtrip(characters) -
The rstrip() method removes any character at the end of the string .


With no argument, strip(), lstrip() and rstrip() use whitespace to remove.

## Has two leading spaces and a trailing
>>> value = " a line "
# Remove left spaces.
>>> value1 = value.lstrip()
>>> print("[" + value1 + "]")
[a line ]
                
# Remove right spaces.
>>> value2 = value.rstrip()
>>> print("[" + value2 + "]")
[ a line]
                
# Remove left and right spaces.
>>> value3 = value.strip()
>>> print("[" + value3 + "]")
[a line]
                
# Remove the given characters
>>> value = ",,,,,rrttgg.....banana....rrr"
>>> x = value.strip(",.grt")
>>> print(x)
banana

# Strip all digits
# ... Also remove equals sign and comma
>>> value = "50342=Data,231"
>>> result = value.strip ("0123456789=,")
>>> print(result)
Data
                

23. rjust(length, character) -
The rjust() method will right align the string, using a specified character (space is default) as the fill character.

length : specifies the length of returning string.
character : specifies to fill the left-side space of the string. default is " " (space).

>>> s = "Hello"
>>> result = s.rjust(10)
>>> print("[" + result + "]")
[     Hello]

>>> result = s.rjust(10,'.')
>>> print("[" + result + "]")
[.....Hello]
>>>

24. ljust(length, character) -
The ljust() method will left align the string, using a specified character (space is default) as the fill character.

length : specifies the length of returning string.
character : specifies to fill the right-side space of the string. default is " " (space).

>>> s = "Hello"
>>> result = s.ljust(10)
>>> print("[" + result + "]")
[Hello     ]

>>> result = s.ljust(10,'.')
>>> print("[" + result + "]")
[Hello.....]
>>>

25. center(length, character) -
The center() method will center align the string, using a specified character (space is default) as the fill character.

length : specifies the length of returning string.
character : specifies to fill the space on both side of the string. default is " " (space).

>>> s = "Hello"
>>> result = s.center(10)
>>> print("[" + result + "]")
[  Hello   ]

>>> result = s.center(10,'.')
>>> print("[" + result + "]")
[..Hello...]
>>>

26. zfill(length) -
The zfill() method adds zeros (0) at the beginning of the string.

length : specifies the length of returning string.

>>> s1 = "hello"
>>>s2 = "Welcome to prowess apps"
>>>s3 = "10.000"

>>>print(s1.zfill(10))
00000hello
>>>print(s2.zfill(10))
Welcome to prowess apps
>>>print(s3.zfill(10))
000010.000
>>>

27. startswith(str, start, end) -
The startswith() method returns True if the string starts with the specified value(str), otherwise False.

>>> phrase = "cat, dog and bird"
# See if the phrase starts with these strings
>>> if phrase.startswith("cat"):
	print(True)

True

>>> if phrase.startswith ("cat, dog"):
	print(True)

True

# It does not start with this string.
>>> if not phrase.startswith("elephant"):
	print(False)

False
>>>

28. endswith(str, start, end) -
The endswith() method returns True if the string ends with the specified value(str), otherwise False.

>>> url = "http://www.rediffmail.com/"
# Test the end of the url
>>> if url.endswith("/"):
	print("Ends with slash")
	
Ends with slash
>>> if url.endswith (".com/"):
	print("Ends with .com/")
	
Ends with .com/

# Does not end in a question mark
>>> if url.endswith("?")==False:
	print(False)

False
         

29. casefold() -
The casefold() method returns a string where all the characters are in lower case.

>>> s = "This is Python Prowess app"
>>> x = s.casefold()
>>> print(x)
this is python prowess app
>>>
         

30. isidentifier() -
The isidentifier() method returns True if string is valid identifier otherwise False.

>>> s = "Demo"
>>> x = s.isidentifier()
>>> print(x)
True
>>> s = "1Demo"
>>> x = s.isidentifier()
>>> print(x)
False
>>>
         

31. isspace() -
The isspace() method returns True if all the characters in a string are whitespaces, otherwise False.

>>> s = "   "
>>> x = s.isspace()
>>> print(x)
True
>>>
         

32. partition(value) -
The partition() method searches for specified value, split into three parts and return tuple.

The first element of tuple is string before the specified value.

The second element of tuple is specified value.

The third element of tuple is string after the specified value.

>>> s = "this python prowess app"
>>> x = s.partition("python")
>>> print(x)
('this ', 'python', ' prowess app')
>>> x = s.partition("this")
>>> print(x)
('', 'this', ' python prowess app')
>>>

33. replace(oldvalue, newvalue, count) -
The replace() method replaces the oldvalue with the newvalue.

count is optional, if not specified replace all the matching oldvalue to the newvalue, else number of times we specify.

>>> s = "this is my string... ok! this is an example"
>>> s1 = s.replace("is","was")
>>> print(s1)
thwas was my string... ok! thwas was an example

>>> s1 = s.replace("is","was",3)
>>> print(s1)
thwas was my string... ok! thwas is an example
                

34. swapcase() -
The swapcase() method chage the lowercase letter to uppercase and uppercase letters to lowercase.

>>> s = "Python Prowess"
>>> s1 = s.swapcase()
>>> print(s1)
pYTHON pROWESS
>>> 

Next topic is for Loop




 






Training For College Campus

We offers college campus training for all streams like CS, IT, ECE, Mechanical, Civil etc. on different technologies like
C, C++, Data Structure, Core Java, Advance Java, Struts Framework, Hibernate, Python, Android, Big-Data, Ebedded & Robotics etc.

Please mail your requirement at info@prowessapps.in


Projects For Students

Students can contact us for their projects on different technologies Core Java, Advance Java, Android etc.

Students can mail requirement at info@prowessapps.in


CONTACT DETAILS

info@prowessapps.in
(8AM to 10PM):

+91-9026070669 , +91-9451396824

© 2016, prowessapps.in, All rights reserved