Strings & Characters

Access by index: str[i]

Clone strings: str*2

Length of strings: len(str)

Useful Methods#

Method NameUseExplanation a string centered in a field of size w
countastring.count(item)Returns the number of occurrences of item in the string
ljustastring.ljust(w)Returns a string left-justified in a field of size w
lowerastring.lower()Returns a string in all lowercase
rjustastring.rjust(w)Returns a string right-justified in a field of size w
findastring.find(item)Returns the index of the first occurrence of item
splitastring.split(schar)Splits a string into substrings at schar
indexastring.index(str, beg=0, end=len(astring))Same as find(), but raises exception if sub is not found
rindexastring.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
lowerastring.lower()Converts string to uppercase
upperastring.upper()Converts string to lowercase

Note: As compared to lists, strings cannot be modified - strings are immutable.

Sorting a String#

sorted(str_s) does the job of converting a string into an array of its sorted characters. Returns the array.

Reversing String#

text = "hello"
text_reversed = text[::-1]

Replacing Characters in a String#

We 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.

# old โ€“ old substring you want to replace.
# new โ€“ new substring which would replace the old substring.
# count โ€“ the number of times you want to replace the old
# substring with the new substring. (Optional )
string.replace(old, new, count)

Character Case Operations#

isupper(), islower(), lower(), upper()

Check if Alphanumeric#

To check if a character is alphanumeric, use ch.isalnum().