Python | String Methods
Slicing
slicing is used for to get a range of Characters from String
range is define in start index , colon and end index
in that range , start index is included but end index is excluded at printing time.
the First character index is start from Zero (0)
Example
str = "Hello Welcome"
print(str[2:5])
print(str[:5])
print(str[2:])
Output
'llo'
'Hello'
'llo Welcome'
Negative Indexing
Negative Indexing is Counting From End of the string
For Example string is "Hello"
-1 index 'O' character
-2 index 'l' character
-3 index 'l' character
-4 index 'e' character
Example
str = "Hello Welcome"
print(str[-5:-2])
Output
'lco'
Modify String
Python has Some built in Methods like upper(),lower(),strip() etc
lowe() Method
lower() Method is return the lowercase strings
Example
str = "HELLO WELCOME "
print(str.lower()) # Return 'hello welcome'
upper() Method
upper() Method is return the uppercase strings
Example
str = "hello welcome"
print(str.upper()) # Return 'HELLO WELCOME'
strip() Method
strip() Method is return the remove whitespace from strings
Example
str = " hello welcome"
print(str.strip()) # Return 'hello welcome'
replace() Method
replace() Method is used for replace one string to another string.
Example
str = "hello welcome"
print(str.replace("h","i")) # Return 'hello welcome' to 'jello welcome'
split() Method
split() Method is return a list where the text between the specified separator becomes the list items
Example
str = "hello welcome"
print(str.split(",")) # Return 'hello welcome' to ['hello','welcome']