Strings and String Operations
A string is a sequence of characters. We combine, slice, measure and search strings to process text data.
All topics (7 of 11)
Chapter 1. Python Basics
Chapter 2. Lists and Strings
Chapter 3. Functions and Modules
Chapter 4. Working with Files
A string (str) is a sequence of characters in quotation marks: s = "informatika". Like a list, every character has an index: s[0] is “i”, s[-1] is “a”. The length is given by len(s). Unlike a list, a string item cannot be changed directly: s[0] = "I" causes an error.
Several operations work on strings. + joins two strings ("info" + "rmatika"), * repeats ("ha" * 3 gives “hahaha”). A slice cuts out a part: s[0:4] is “info”, s[4:] is “rmatika”, and s[::-1] is the string reversed. In a slice the last index is not included.
Python has many ready-made string methods. s.upper() and s.lower() change letters to uppercase or lowercase, s.find("mat") returns the position of a substring (or -1 if not found), s.replace("a", "o") replaces, and s.count("a") counts characters. text.split() splits a text into a list of words, and " ".join(words) puts a list back into a string.
A string can also be walked through character by character with a for loop: for ch in s:. For example, to count vowels the condition if ch in "aeiou": fits. A string of digits becomes a number with int("25"), and a number becomes a string with str(25); otherwise an action like "5" + 5 causes an error.
Key takeaways
- A string is a sequence of characters; indexes and slices (
s[1:4]) work. - A string cannot be changed directly; a new string is created.
upper,lower,find,replaceandsplitare the most used methods.int()andstr()convert between strings and numbers.
Practice tasks
- Print the word entered by the user in reverse order (
s[::-1]) and check whether it is a palindrome (reads the same both ways). - Find the number of words in an entered sentence using
split()andlen(). - Count the vowels in a sentence using a
forloop and theinoperator.
Review questions
Test yourself: think first, then reveal the answer.
1What does `s[1:4]` give if `s = "python"`?Show answerHide answer
“yth” — from index 1 to index 3; index 4 is not included.2Why does `"5" + 5` cause an error?Show answerHide answer
A string and a number cannot be added; first make the types match with `int("5")` or `str(5)`.
0 of 11 topics completed
Sign in to mark