In Python, Strings can be created by simply enclosing characters in quotes. Python does not support character types. These are treated as length-one strings, and are also considered as substrings. Substrings are immutable and can’t be changed once created.
Concatenation and Repetition
- Strings are concatenated with the +sign:
>>> ‘abc’+‘def’
‘abcdef’
- Strings are repeated with the *sign:
>>> ‘abc’*3
‘abcabcabc’
Indexing and Slicing Operation
- Python starts indexing at ‘0’
- A string s will have indexes running from 0 to len(s)-1 (where len(s) is the length of s) in integer quantities.
- S[i] fetches the ith element in s.
Built-in String Methods
Following are the built-in String Methods that can be used in Python:
- capitalize() – Capitalizes the first letter of string.
- count(str, beg= 0, end=len(string)) – Counts how many times str occurs in string or in a substring of string if beginning index ‘beg’ and ending index ‘end’ are given.
- encode(encoding=‘UTF-8’,errors=‘strict’) – Returns encoded string version of string; on error, default raises a ValueError, unless the error is given with ‘ignore’ or ‘replace’.
- decode (encoding=‘UTF-8’, errors=‘strict’) – Decodes the string using the codec registered for Encoding. Encoding defaults to the default string function.
- index(str, beg=0, end=len(string))- Same as find(), but raises an exception if str is not found.
- max(str)- Returns the max alphabetical character from the string str.
- min(str)- Returns the min alphabetical character from the string str.
- replace(old, new [, max])- Replaces all occurrences of ‘old’ in string with ‘new’ or maximum occurrences if max is given.
upper()- Converts lowercase letters in a string to uppercase.
Got a question for us? Mention them in the comments section and we will get back to you.
Related Posts: