Strings & Characters
Access by index: str[i]
Clone strings: str*2
Length of strings: len(str)
#
Useful MethodsMethod Name | Use | Explanation |
---|---|---|
center | astring.center(w) | Returns a string centered in a field of size w |
count | astring.count(item) | Returns the number of occurrences of item in the string |
ljust | astring.ljust(w) | Returns a string left-justified in a field of size w |
lower | astring.lower() | Returns a string in all lowercase |
rjust | astring.rjust(w) | Returns a string right-justified in a field of size w |
find | astring.find(item) | Returns the index of the first occurrence of item |
split | astring.split(schar) | Splits a string into substrings at schar |
index | astring.index(str, beg=0, end=len(astring)) | Same as find() , but raises exception if sub is not found |
rindex | astring.rindex(str, beg=0 end=len(astring)) | Returns last index where the substring str is found, or raises an exception if no such index exists |
lower | astring.lower() | Converts string to uppercase |
upper | astring.upper() | Converts string to lowercase |
Note: As compared to lists, strings cannot be modified - strings are immutable.
#
Sorting a Stringsorted(str_s)
does the job of converting a string into an array of its sorted characters. Returns the array.
#
Reversing String#
Replacing Characters in a StringWe can use the replace
function to replace characters:
replace() is an inbuilt function in Python programming language that returns a copy of the string where all occurrences of a substring is replaced with another substring.
#
Character Case Operationsisupper()
, islower()
, lower()
, upper()
#
Check if AlphanumericTo check if a character is alphanumeric, use ch.isalnum()
.