String Operations#

[1]:
"heLlo World".capitalize() # first letter uppercase all other lower
[1]:
'Hello world'
[2]:
"hello World".casefold() # lowercase
[2]:
'hello world'
[3]:
"Hello World".center(50) # put the string in center
[3]:
'                   Hello World                    '
[4]:
" Hello World ".center(50,"x") #put the string in center and fill padding with x
[4]:
'xxxxxxxxxxxxxxxxxx Hello World xxxxxxxxxxxxxxxxxxx'
[5]:
"Hello World Hello".count("Hello") # count freq
[5]:
2
[6]:
"Hello World".endswith("d")
[6]:
True
[7]:
"Hello\tWorld".expandtabs(4) # expand \t tabs with 4 spaces
[7]:
'Hello   World'
[8]:
"Hello World".find("World") # returns index from which word's first occurance is starting otherwise -1
[8]:
6
[9]:
"Hello World".index("World")
[9]:
6
[10]:
"Hello World".index("World",6,10) # index and find is similar only difference is that this will throw value error
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-10-a7a86f317d1d> in <module>
----> 1 "Hello World".index("World",6,10) # index and find is similar only difference is that this will throw value error

ValueError: substring not found
[20]:
"Hello World".isalnum(),"123".isalnum() #alphnumeric
[20]:
(False, True)
[16]:
"HelloWorld".isalpha(),"Hello World".isalpha()
[16]:
(True, False)
[22]:
"12".isdecimal(),"Hello World".isdecimal()
[22]:
(True, False)
[24]:
"12".isdigit(),"Hello World".isdigit()
[24]:
(True, False)
[25]:
"12".isnumeric(),"Hello World".isnumeric()
[25]:
(True, False)
[27]:
"Hello World".isspace(), "             ".isspace() # if string contains only spaces
[27]:
(False, True)
[35]:
" ".join(("hello","world","!","Nishant")) # join by separator
[35]:
'hello world ! Nishant'
[37]:
x = {"fname":"Nishant","lname":"Baheti"}
" ".join(x.values())
[37]:
'Nishant Baheti'
[39]:
"Hello World".lower()
[39]:
'hello world'
[40]:
"Hello World".upper()
[40]:
'HELLO WORLD'
[46]:
x = "Jello world".maketrans("J","H")
"Jello world".translate(x)
[46]:
'Hello world'
[48]:
"I could eat bananas all day, bananas bananas are my favorite fruit".rpartition("bananas") # starts from last occurance
[48]:
('I could eat bananas all day, bananas ', 'bananas', ' are my favorite fruit')
[49]:
"Hello, world, Nishant".split(",")
[49]:
['Hello', ' world', ' Nishant']
[51]:
"    Hello World".lstrip()
[51]:
'Hello World'
[52]:
"Hello World   ".rstrip()
[52]:
'Hello World'
[53]:
"        Hello World      ".strip()
[53]:
'Hello World'
[54]:
"Hello World".startswith("H")
[54]:
True
[55]:
"Ello There maTe".swapcase()
[55]:
'eLLO tHERE MAtE'
[56]:
"my name is nishant and i am exploring string methods in python".title()
[56]:
'My Name Is Nishant And I Am Exploring String Methods In Python'
[62]:
"500".zfill(20)
[62]:
'00000000000000000500'