Python for Programmers: More String Methods
Welcome to the More String Methods lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
We've seen a few string methods already. This lesson will cover some more common string methods.
.upperconverts the entire string to uppercase.>
"Amir".upper()Result:
'AMIR'
.lowerconverts it to lowercase.>
"Amir".lower()Result:
'amir'
The
.splitmethod splits a string by a given separator. It gives us a list of the strings that occur between the separators.>
"a,b,c".split(",")Result:
>
"a:b".split(":")Result:
['a', 'b']
If the string doesn't contain the separator,
.splitreturns a list with the original string.>
"a,b,c".split("%")Result:
['a,b,c']
The separator can be multiple characters. Python only breaks the string in places where the entire separator appears together.
>
"a, b, c".split(", ")Result:
['a', 'b', 'c']
It's easy to make mistakes in the separator string. For example, our string might be
"a, b, c". If we split on just",", then our list will include the spaces in its strings.>
"a, b, c".split(",")Result:
If the string starts with the separator, we get an empty string
""as the first element.>
"$17$18".split("$")Result:
If the string ends with the separator, we get an empty string as the last element.
>
"17.18.".split(".")Result:
['17', '18', '']
>
":abc:".split(":")Result:
['', 'abc', '']
.splitlinessplits multi-line text into a list of lines, but we don't need to provide a separator. It handles newlines (\n), carriage returns (\r), and Windows-style line terminators (\r\n). This makes.splitlineswork across different operating systems. Getting the same effect with.splitwould take a lot more work.>
"Amir\nBetty\r\nCindy".splitlines()Result:
['Amir', 'Betty', 'Cindy']
.joinis the opposite of.split. It combines list elements into one string, inserting the provided string between the elements.>
cat_names = ["Keanu", "Ms. Fluff", "Wilford"]", ".join(cat_names)Result:
>
animal_names = ["cat", "dog", "owl"]", ".join(animal_names)Result:
'cat, dog, owl'
If we combine
.joinand.split, we get the list that we started with.>
cat_names = ["Keanu", "Ms. Fluff", "Wilford"]", ".join(cat_names).split(", ")Result:
['Keanu', 'Ms. Fluff', 'Wilford']
.stripremoves leading and trailing whitespace. That includes spaces, newlines (\n), line feeds (\r), tabs (\t), and some other less-common whitespace characters.>
" Hello, Amir\n".strip()Result:
'Hello, Amir'
Without an argument,
.stripremoves whitespace, as shown above. But we can also provide acharsargument, which is the set of characters to remove..stripwill remove any of the characters we provide from the beginning and end of the string.(Note that unlike
.split, the characters don't have to occur together.)>
"!!!1000.!..".strip(".!")Result:
'1000'
>
"!10!00.".strip(".!")Result:
'10!00'
We can replace a substring with
.replace(old, new).>
"Hello, NAME".replace("NAME", "Amir")Result:
'Hello, Amir'
.replacereplaces all instances of the old string, not just the first one.>
"NAME,36,NAME".replace("NAME", "Amir")Result:
'Amir,36,Amir'
Here's a code problem:
Write a loop that takes a comma-separated string of integers like
"1,2,3",.splits them into a list, then sums them together. As a reminder,int()converts strings into numbers.def sum_string(s):total = 0for value in s.split(","):total += int(value)return totalassert sum_string("5,3,1,2,4") == 15assert sum_string("1,10,100,1000") == 1111assert sum_string("0") == 0- Goal:
No errors.
- Yours:
No errors.