Python challenge: Exploring strings
Here are some functions that can be applied on strings. Let’s take “lorem ipsum” as a dummy example:
Printing a string
Getting the length of a string
Capitalize a string
Checking if a string ends in a certain way
Checking if a string is lower case
Checking if a string is numeric
Checking if a string contains a white space
Testing for string equality
This check is quite simple, but somewhat incorrect as it is case-sensitive. If you want to compare two strings without case-sensitivity, the following is more suitable:
Checking if a string contains a certain substring
This will return true, if the string contains the substring in question.
Checking at which index a certain substring appears
This will return a number indicating where the substring in question occurs. If the number is -1, then the substring is not present.
Checking how often a substring appears in a string
The easiest and most common way to check that is by using count
:
Note that count
ignores overlapping occurences. Here, the number 2
is printed.
Iterating through a string
Another way could be as follows:
This is a bit shorter and more pythonic.
Splitting a string
Here, the string will be splitted at each white space. You can use other separators as well.
Removing a character in a string
Inserting a character into a string
This will insert a dash after the fifth character.
Using the not
operator with strings
Further resources
Example code for the string operations above can be found here
My python challenge