Python String Operations and Methods
String
A string is a sequence of characters enclosed in quotation. We can use single (‘‘), double(“ “) or triple(‘ ‘ ‘ ‘ ‘ ‘ ) quotes to define a string in python.
The characters present in a string can be any digit, letter, symbols or space. String in python is an immutable data type i.e once a value is assigned it cannot be changed later.
Syntax : stringname= ” abcd1234@#$%^ “
Example:
String Operations
· Concatenation
· Replication
· Indexing
· Slicing
Concatenation
Concatenation is the operation of joining two or more strings together.
Python strings can be joined using the concatenation operator (+).
Syntax: str= str1 + str2
Example:
Replication
Python allows us to repeat a string multiple times with the help of (*) operator.
Syntax: stringname * integer
Example:
Indexing
Indexing allows us to access individual characters in a string by using a numeric value.
Example:
Slicing
Slicing is about obtaining a sub-string from the given string by slicing it.
Syntax: string[start : end : step]
Note:
· Start is inclusive
· End is Exclusive
· Step is increment between each index for slicing. (Optional)
Example:
String Methods
Python has some built-in methods that you can use on strings.
Some of them are listed below:
· lower() : converts a string into lower case.
· upper() : converts a string into upper case.
· title() : converts the first letter of each word to upper case.
· capitalize() : converts the first character to upper case.
· swapcase() : converts lower case to upper case and vice versa.
· find() : finds the string for a specified value and return the position.
· count() : returns the number of occurance of a specified value in a string.
· replace() : It is used to replace a value with another specified value.
· format() : formats the specified value and inserts them inside the string’s placeholder.
Output:
· split() : splits/breaks the string at a specified point and returns a list.
· lstrip() : returns a left trim version of a string.
· rstrip() : returns a right trim version of a string.
· strip() : removes spaces at the beginning and at the end of the string.
· center() : returns a centered string.
· startswith() : it is used to check, if the string starts with a specified value.
· endswith() : it is used to check, if the string ends with a specified value.
End Notes
In this article, we have covered python string operations and methods that will help you understand python better.