Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/master/17-Advanced Python Objects and Data Structures/02-Advanced Strings.ipynb
Views: 648
Advanced Strings
String objects have a variety of methods we can use to save time and add functionality. Let's explore some of them in this lecture:
Changing case
We can use methods to capitalize the first word of a string, or change the case of the entire string.
Remember, strings are immutable. None of the above methods change the string in place, they only return modified copies of the original string.
To change a string requires reassignment:
Location and Counting
Formatting
The center()
method allows you to place your string 'centered' between a provided string with a certain length. Personally, I've never actually used this in code as it seems pretty esoteric...
The expandtabs()
method will expand tab notations \t
into spaces:
is check methods
These various methods below check if the string is some case. Let's explore them:
isalnum()
will return True if all characters in s are alphanumeric
isalpha()
will return True if all characters in s are alphabetic
islower()
will return True if all cased characters in s are lowercase and there is at least one cased character in s, False otherwise.
isspace()
will return True if all characters in s are whitespace.
istitle()
will return True if s is a title cased string and there is at least one character in s, i.e. uppercase characters may only follow uncased characters and lowercase characters only cased ones. It returns False otherwise.
isupper()
will return True if all cased characters in s are uppercase and there is at least one cased character in s, False otherwise.
Another method is endswith()
which is essentially the same as a boolean check on s[-1]
Built-in Reg. Expressions
Strings have some built-in methods that can resemble regular expression operations. We can use split()
to split the string at a certain element and return a list of the results. We can use partition()
to return a tuple that includes the first occurrence of the separator sandwiched between the first half and the end half.
Great! You should now feel comfortable using the variety of methods that are built-in string objects!