Python String Methods ?

PythonServer Side ProgrammingProgramming

Python provides lots of built-in methods which we can use on strings.

Below are the list of string methods available in Python 3.

Method
Description
Examples
capitalize()
Returns a copy of the string with its first character capitalized and the rest lowercased.
>>> mystring = "hello python"
>>> print(mystring.capitalize())
Hello python
Casefold()
Returns a casefolded copy of the string. Casefolded strings may be used for caseless matching.
>>> mystring = "hello PYTHON"
>>> print(mystring.casefold())
hello python
Center(width, [fillchar])
Returns the string centered in a string of length width. Padding can be done using the specified fillchar (the default padding uses an ASCII space). The original string is returned if width is less than or equal to len(s)
>>> mystring = "Hello"
>>> x = mystring.center(12,
"-")
>>> print(x)
---Hello----
Count(sub, [start], [end])
Returns the number of non-overlapping occurrences of substring (sub) in the range [start, end]. Optional arguments startand end are interpreted as in slice notation.
>>> mystr = "Hello Python"
>>> print(mystr.count("o"))
2
>>> print(mystr.count("th"))
1
>>> print(mystr.count("l"))
2
>>> print(mystr.count("h"))
1
>>> print(mystr.count("H"))
1
>>> print(mystr.count("hH"))
0
Encode(encoding = “utf-g”, errors = “strict”)
Returns an encoded version of the string as a bytes object. The default encoding is utf-8. errors may be given to set a different error handling scheme. The possible value for errors are:
  • strict (encoding errors raise a UnicodeError)

  • ignore

  • replace

  • xmlcharrefreplace

  • backslashreplace

  • any other name registered via codecs.register_error()

 
>>> mystr = 'python!'
>>> print('The string is:',
mystr)
The string is: python!
>>> print('The encoded
version is: ',
mystr.encode("ascii",
"ignore"))
The encoded version is:
b'python!'
>>> print('The encoded
version (with replace) is:',
mystr.encode("ascii",
"replace"))
The encoded version (with
replace) is: b'python!'
endswith(suffix, [start], [end])
Returns True if the string ends with the specified suffix, otherwise it returns False.
>>> mystr = "Python"
>>>
print(mystr.endswith("y"))
False
>>>
print(mystr.endswith("hon"))
True
Expandtabs(tabsize=8)
Returns a copy of the string where all tab characters are replaced by one or more spaces, depending on the current column and the given tab size.
>>> mystr = "1\t2\t3"
>>> print(mystr)
1 2 3
>>>
print(mystr.expandtabs())
1 2 3
>>>
print(mystr.expandtabs(tabsi
ze=15))
1 2
3
>>>
print(mystr.expandtabs(tabsi
ze=2))
1 2 3
Find(sub, [start], [end])
Returns the lowest index in the string where substring sub is found within the slice s[start:end].
>>> mystring = "Python"
>>>
print(mystring.find("P"))
0
>>>
print(mystring.find("on"))
4
Format(*args, **kwargs)
Performs a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces {}.
>>> print("{} and
{}".format("Apple",
"Banana"))
Apple and Banana
>>> print("{1} and
{0}".format("Apple",
"Banana"))
Banana and Apple
>>> print("{lunch} and
{dinner}".format(lunch="Peas
", dinner="Beans"))
Peas and Beans
format_map(mapping)
Similar to format(**mapping), except that mapping is used directly and not copied to a dictionary.
>>> lunch = {"Food":
"Pizza", "Drink": "Wine"}
>>> print("Lunch: {Food},
{Drink}".format_map(lunch))
Lunch: Pizza, Wine
>>> class Default(dict):
def __missing__(self,
key):
return key
>>> lunch = {"Drink":
"Wine"}
>>> print("Lunch: {Food},
{Drink}".format_map(Default(
lunch)))
Lunch: Food, Wine
Index(sub, [start], [end])
Searches the string for a specified value and returns the position of where it was found
>>> mystr = "HelloPython"
>>> print(mystr.index("P"))
5
>>>
print(mystr.index("hon"))
8
>>> print(mystr.index("o"))
4
isalnum
Returns True if all characters in the string are alphanumeric
>>> mystr = "HelloPython"
>>> print(mystr.isalnum())
True
>>> a = "123"
>>> print(a.isalnum())
True
>>> a= "$*%!!!"
>>> print(a.isalnum())
False
Isalpha()
Returns True if all characters in the string are in the alphabet
>>> mystr = "HelloPython"
>>> print(mystr.isalpha())
True
>>> a = "123"
>>> print(a.isalpha())
False
>>> a= "$*%!!!"
>>> print(a.isalpha())
False
Isdecimal()
Returns True if all characters in the string are decimals
>>> mystr = "HelloPython"
>>> print(mystr.isdecimal())
False
>>> a="1.23"
>>> print(a.isdecimal())
False
>>> c = u"\u00B2"
>>> print(c.isdecimal())
False
>>> c="133"
>>> print(c.isdecimal())
True
Isdigit()
Returns True if all characters in the string are digits
>>> c="133"
>>> print(c.isdigit())
True
>>> c = u"\u00B2"
>>> print(c.isdigit())
True
>>> a="1.23"
>>> print(a.isdigit())
False
isidentifier()
Returns True if the string is an identifier
>>> c="133"
>>> print(c.isidentifier())
False
>>> c="_user_123"
>>> print(c.isidentifier())
True
>>> c="Python"
>>> print(c.isidentifier())
True
Islower()
Returns True if all characters in the string are lower case
>>> c="Python"
>>> print(c.islower())
False
>>> c="_user_123"
>>> print(c.islower())
True
>>> print(c.islower())
False
Isnumeric()
Returns True if all characters in the string are numeric
>>> c="133"
>>> print(c.isnumeric())
True
>>> c="_user_123"
>>> print(c.isnumeric())
False
>>> c="Python"
>>> print(c.isnumeric())
False
isprintable()
Returns True if all characters in the string are printable
>>> c="133"
>>> print(c.isprintable())
True
>>> c="_user_123"
>>> print(c.isprintable())
True
>>> c="\t"
>>> print(c.isprintable())
False
isspace()
Returns True if all characters in the string are whitespaces
>>> c="133"
>>> print(c.isspace())
False
>>> c="Hello Python"
>>> print(c.isspace())
False
73
>>> c="Hello"
>>> print(c.isspace())
False
>>> c="\t"
>>> print(c.isspace())
True
istitle()
Returns True if the string follows the rules of a title
>>> c="133"
>>> print(c.istitle())
False
>>> c="Python"
>>> print(c.istitle())
True
>>> c="\t"
>>> print(c.istitle())
False
isupper()
Returns True if all characters in the string are upper case
>>> c="Python"
>>> print(c.isupper())
False
>>> c="PYHTON"
>>> print(c.isupper())
True
>>> c="\t"
>>> print(c.isupper())
False
join(iterable)
Joins the elements of an iterable to the end of the string
>>> a ="-"
>>> print(a.join("123"))
1-2-3
>>> a="Hello Python"
>>> a="**"
>>> print(a.join("Hello
Python"))
H**e**l**l**o**
**P**y**t**h**o**n
ljust(width[,fillchar])
Returns a left justified version of the string
>>> a="Hello"
>>> b = a.ljust(12, "_")
>>> print(b)
Hello_______
lower()
Converts a string into lower case
>>> a = "Python"
>>> print(a.lower())
Python
lstrip([chars])
Returns a left trim version of the string
>>> a = " Hello "
>>> print(a.lstrip(), "!")
Hello
maketrans(x[, y[, z]])
Returns a translation table to be used in translations
>>> frm = "SecretCode"
>>> to = "4203040540"
>>> trans_table =
str.maketrans(frm,to)
>>> sec_code = "Secret
Code".translate(trans_table)
>>> print(sec_code)
400304 0540
partition(sep)
Returns a tuple where the string is parted into three parts
>>> mystr = "Hello-Python"
>>> print(mystr.partition("-
"))
('Hello', '-', 'Python')
74
>>>
print(mystr.partition("."))
('Hello-Python', '', '')
replace(oldnew[,count])
Returns a string where a specified value is replaced with a specified value
>>> mystr = "Hello Python.
Hello Java. Hello C++."
>>>
print(mystr.replace("Hello",
"Bye"))
Bye Python. Bye Java. Bye
C++.
>>>
print(mystr.replace("Hello",
"Hell", 2))
Hell Python. Hell Java.
Hello C++.
rfind(sub[, start[,end]])
Searches the string for a specified value and returns the last position of where it was found
>>> mystr = "Hello-Python"
>>> print(mystr.rfind("P"))
6
>>> print(mystr.rfind("-"))
5
>>> print(mystr.rfind("z"))
-1
rindex(sub[, start[,end]])
Searches the string for a specified value and returns the last position of where it was found
>>> mystr = "Hello-Python"
>>> print(mystr.rindex("P"))
6
>>> print(mystr.rindex("-"))
5
>>> print(mystr.rindex("z"))
Traceback (most recent call
last):
File "<pyshell#253>", line
1, in <module>
print(mystr.rindex("z"))
ValueError: substring not
found
rjust(width[,fillchar])
Returns the string right justified in a string of length width.
>>> mystr = "Hello Python"
>>> mystr1 = mystr.rjust(20,
"-")
>>> print(mystr1)
--------Hello Python
rpartition(sep)
Returns a tuple where the string is parted into three parts
>>> mystr = "Hello Python"
>>>
print(mystr.rpartition("."))
('', '', 'Hello Python')
>>> print(mystr.rpartition("
"))
('Hello', ' ', 'Python')
rsplit(sep=None, maxsplit=-1)
Splits the string at the specified separator, and returns a list
>>> mystr = "Hello Python"
>>> print(mystr.rsplit())
['Hello', 'Python']
>>> mystr = "Hello-Python-
Hello"
>>>
print(mystr.rsplit(sep="-",
maxsplit=1))
['Hello-Python', 'Hello']
rstrip([chars])
Returns a right trim version of the string
>>> mystr = "Hello Python"
>>> print(mystr.rstrip(),
"!")
Hello Python !
>>> mystr = "------------
Hello Python-----------"
>>> print(mystr.rstrip(), "-
")
------------Hello Python----
------- -
>>> print(mystr.rstrip(),
"_")
------------Hello Python----
------- _
split(sep=None, maxsplit=-1)
Splits the string at the specified separator, and returns a list
>>> mystr = "Hello Python"
>>> print(mystr.split())
['Hello', 'Python']
>>> mystr1="Hello,,Python"
>>> print(mystr1.split(","))
['Hello', '', 'Python']
splitlines([keepends])
Splits the string at line breaks and returns a list
>>> mystr = "Hello:\n\n
Python\r\nJava\nC++\n"
>>>
print(mystr.splitlines())
['Hello:', '', ' Python',
'Java', 'C++']
>>>
print(mystr.splitlines(keepe
nds=True))
['Hello:\n', '\n', '
Python\r\n', 'Java\n',
'C++\n']
startswith(prefix[,start[, end]])
Returns true if the string starts with the specified value
>>> mystr = "Hello Python"
>>>
print(mystr.startswith("P"))
False
>>>
print(mystr.startswith("H"))
True
>>>
print(mystr.startswith("Hell
"))
True
strip([chars])
Returns a trimmed version of the string
>>> mystr = "
Hello Python
"
>>> print(mystr.strip(),
"!")
Hello Python !
>>> print(mystr.strip(), "
")
Hello Python
swapcase()
Swaps cases, lower case becomes upper case and vice versa
>>> mystr = "Hello PYthon"
>>> print(mystr.swapcase())
hELLO python
title()
Converts the first character of each word to upper case
>>> mystr = "Hello PYthon"
>>> print(mystr.title())
Hello Python
>>> mystr = "HELLO JAVA"
>>> print(mystr.title())
Hello Java
translate(table)
Returns a translated string
>>> frm = "helloPython"
>>> to = "40250666333"
>>> trans_table =
str.maketrans(frm, to)
>>> secret_code = "Secret
Code".translate(trans_table)
>>> print(secret_code)
S0cr06 C3d0
upper()
Converts a string into upper case
>>> mystr = "hello Python"
>>> print(mystr.upper())
HELLO PYTHON
zfill(width)
Fills the string with a specified number of 0 values at the beginning
>>> mystr = "999"
>>> print(mystr.zfill(9))
000000999
>>> mystr = "-40"
>>> print(mystr.zfill(5))
-0040
raja
Published on 09-Apr-2019 07:36:42
Advertisements