Python challenge: Exploring strings
Here are some functions that can be applied on strings. Let’s take “lorem ipsum” as a dummy example:
lorem = "lorem ipsum"
Printing a string
print("Dummy string: ", lorem)
Getting the length of a string
print("Length: ",len(lorem))
Capitalize a string
print("Capitalized: " + lorem.capitalize())
Checking if a string ends in a certain way
print("endswith 'ipsum': " + str(lorem.endswith("ipsum")))
Checking if a string is lower case
print("islower: " + str(lorem.islower()))
Checking if a string is numeric
print("isnumeric: " + str(lorem.isnumeric()))
Checking if a string contains a white space
print("isspace: " + str(lorem.isspace()))
Testing for string equality
lorem2 = "lorem ipsum"
if lorem == "lorem ipsum":
print("The strings are equal")
else:
print("The strings are not equal")
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:
lorem2 = "lorem ipsum"
if lorem.lower() == lorem2.lower():
print("The strings are equal")
else:
print("The strings are not equal")
Checking if a string contains a certain substring
print("m" in lorem)
print("a" in lorem)
This will return true, if the string contains the substring in question.
Checking at which index a certain substring appears
print("lorem", lorem.find("lorem"))
print("rem", lorem.find("rem"))
print("ips", lorem.find("ips"))
print("abc", lorem.find("abc"))
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
:
teststring = "abbaaaa"
print(teststring.count("aa"))
Note that count
ignores overlapping occurences. Here, the number 2
is printed.
Iterating through a string
i = 0
while i < len(lorem):
print(lorem[i])
i = i +1
Another way could be as follows:
for c in lorem:
print(c)
This is a bit shorter and more pythonic.
Splitting a string
splitted = lorem.split(" ")
for word in splitted:
print(word)
Here, the string will be splitted at each white space. You can use other separators as well.
Removing a character in a string
new_lorem = lorem.replace("m", "")
Inserting a character into a string
new_lorem = lorem[:5] + "-" + lorem[6:]
This will insert a dash after the fifth character.
Using the not
operator with strings
name=""
if not name:
print("the name is not set")
name="abc"
if not name:
print("the name is not set")
else:
print("now the name is set")
Further resources
Example code for the string operations above can be found here
My python challenge