Looking inside a string
A program can use a string as a whole value: read a line of text, join two strings with +, or turn the text "42" into the number 42. Many problems need to look inside the text instead. Programmers, for example, shorten a long word to its first letter, the number of letters in between and its last letter, so internationalization is written i18n and localization is written l10n. To shorten a word this way, a program has to find the word's first letter, its last letter and its length.
A program can do that because a string is a sequence of characters: letters, digits, spaces and punctuation, kept in order. The word hello is a string of five characters, h, e, l, l and o. Most of what works on a list carries over: each character has an index counted from 0, the string has a length, and you read one character by writing its index in square brackets.
Reading one character and the length
s = 'hello'
print(s[0])
print(s[4])
print(len(s))
print(s[-1])Python details
Python has no separate character type. s[0] is itself a string, one character long.
A negative index counts from the end, as it does on a list, so s[-1] is the last character.
| Index | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| Character | h | e | l | l | o |
s[0] is h and s[4] is o. The length is 5, so the indexes run from 0 to 4, just as they did for a list of five numbers.
There is no character at index 5, and reading s[5] stops the program with IndexError: string index out of range.
Abbreviating long words
You now have what the abbreviation from the start of this part needs. The Codeforces problem Way Too Long Words asks for it, for every word longer than 10 letters.
Some words are too long to write out. A word with more than 10 letters is abbreviated as its first letter, the number of letters between the first and the last, and its last letter. Words of 10 letters or fewer stay as they are.
The first line holds , and each of the next lines holds one word. Print each word, abbreviated when it is too long.
Constraints
- Each word has 1 to 100 lowercase letters
Sample · Input
4 word localization internationalization pneumonoultramicroscopicsilicovolcanoconiosis
Output
word l10n i18n p43s
In the sample, word has 4 letters, so it stays. localization has 12 letters: its first is l, its last is n, and between them sit letters, so it becomes l10n. The 2 accounts for the first and last letters, which are written out instead of counted.
For each word the program needs three things: its length, its first character at index 0, and its last character at index length minus one.
n = int(input())
for i in range(n):
w = input()
if len(w) > 10:
print(w[0] + str(len(w) - 2) + w[-1])
else:
print(w)Python details
input() returns the next line of input as a string, with its spaces but without the line break at its end. str(len(w) - 2) turns the number 10 into the string '10', so that + can join it to the two letters.
For pneumonoultramicroscopicsilicovolcanoconiosis, the length is 45, so the program prints p, then , then s.
Writing a line that mixes words and numbers
Output often mixes words and numbers, such as room 12, floor 1. One way to build that line is to turn each number into text with str and join the pieces with +. Python has a shorter way to write it, the f-string: a string with f before its opening quotation mark, in which each expression between braces is replaced by its value, turned into text.
n = 12
print('room ' + str(n) + ', floor ' + str(n // 10))
print(f'room {n}, floor {n // 10}')Both lines print the same text. The f-string needs no str calls, and it looks like the line it prints.
Joining is the whole of the AtCoder problem Strings: it gives two words and asks for the second followed by the first, with no space between them.
Quotation marks and line breaks inside a string
A string written directly in a program, such as 'room ', is a string literal. Some characters cannot be typed directly between its quotation marks. Python accepts single or double quotation marks around a literal, so a string that contains one kind can go between the other. A line break, the backslash, and a quotation mark of the enclosing kind are each written as an escape sequence: a backslash followed by a character. \n stands for a line break, \' for a single quotation mark and \\ for one backslash. Text that spans several lines can also go between triple quotation marks.
print("It's raining")
print('line one\nline two')
poem = """roses
violets"""
print(poem)
print(len('a\nb'))Python details
A triple-quoted string keeps its line breaks exactly as typed, so poem holds a newline between roses and violets.
The last line prints 3, not 4. \n takes two keystrokes to write, but it stands for one character, the newline, so a\nb is three characters: a, a newline and b. When a newline is printed, the text after it starts on a new line, which is how line one and line two came out on separate lines from one string.
Substrings and substring search
A slice of a string works exactly as a slice of a list: s[5:11] is a new string holding the characters at indexes 5 to 10, and s[::-1] is s reversed. A run of consecutive characters like s[5:11] is a substring.
On a list, x in nums asks whether x equals one of the elements. On a string, t in s asks whether t appears anywhere in s as a substring, so it can match several characters at once.
s = 'internationalization'
print('nation' in s)
print(s[5:11])
print(s.find('nation'))
print(s.find('xyz'))
print('ion' in ['nat', 'ion', 'al'])
print('io' in ['nat', 'ion', 'al'])Python details
s.find(t) gives the index where t first appears in s, or -1 when it does not appear.
nation appears in s, starting at index 5, which is why the slice s[5:11], characters long, gives nation back and find returns 5.
The last two lines ask a list instead. 'io' in ['nat', 'ion', 'al'] is false even though io sits inside ion, because a list is asked whether one of its elements equals 'io', and none does.
Searching for a substring lets some problems be answered with one test. Football gives a line of 0s and 1s, the positions of the players, and calls the situation dangerous when at least seven players of one team stand in a row. Seven in a row means that 0000000 or 1111111 appears in the line.
Visiting each character and building a new string
Way Too Long Words looked at only two characters of each word. Most string problems look at every character, and many build another string from them. A small example: given a string of 0s and 1s, swap each 0 for a 1 and each 1 for a 0, so 1011 becomes 0100.
The program starts with an empty string t, of length 0, visits the characters of s in order with a for loop, and adds one character to the end of t for each of them.
Watch how t grows: t + '1' makes a brand-new string, and the name t moves to it.
Step through it, then try the other inputs. The last, 1a, contains a character the program was not written for; decide what the else branch will do with the a before you step through it.
Step through building a new string
With 1a, the program prints 00. The else branch runs for every character that is not 0, so the a turns into a 0 without any error. The program is correct only for the inputs its problem promises, here strings of 0s and 1s.
The AtCoder problem flip (ABC289 A) asks for exactly this program on its own input. Something on It (ABC095 A) uses the same loop with a counter in place of t: it gives three characters, each o or x, and a price of 700 yen plus 100 yen for every o.
Comparing characters by their codes
The swap program compared each character with '0'. A computer can compare characters because it stores each one as a small whole number, its character code. The codes for English letters, digits and punctuation come from a table called ASCII: A is 65, a is 97 and the digit 0 is 48. Comparing two characters compares their codes.
The table puts the letters in alphabetical order, so 'a' < 'b' is true. It also puts every uppercase letter before every lowercase one, since Z is 90 and a is 97.
print(ord('a'))
print(ord('A'))
print(chr(ord('a') + 1))
print('a' < 'b')
print('Z' < 'a')
print('apple' < 'apricot')Python details
ord gives a character's code and chr turns a code back into a one-character string.
Character codes also turn a digit character into its number, which a program needs when it reads a number as text and works with its digits. The digits sit in order from code 48 for 0 to 57 for 9, so a digit's value is its code minus the code of 0.
ord('7') - ord('0') is . int('7') gives the same 7 and reads more plainly.
The last line of the listing compared two whole strings. == asks whether two strings have the same characters in the same order: 'abc' == 'abc' is true and 'abc' == 'ABC' is false. < compares them the way a dictionary orders words: the comparison walks both from the left until they differ. apple and apricot agree on a and p, then p meets r, and since p comes first, apple is smaller. When one string runs out first, as app does against apple, the shorter one is smaller.
The same rule applies to strings made of digits, which compare as text, not as numbers. '10' < '9' is true, because the first characters already differ and 1, code 49, comes before 9, code 57. To compare the numbers, convert both strings first.
Petya and Strings practises this comparison. It compares two words the way a dictionary would, except that case does not count, so aaaa and aaaA are equal, and it asks for -1, 1 or 0 as the first word is smaller than, larger than or equal to the second. w.lower() gives a copy of w with every letter in lowercase; once both words are lowercased, one < test and one == test decide the answer.
Deeper read: letters outside English
ASCII has codes only for English letters, digits, punctuation and a few control characters. Text in other languages, and letters such as é, need a larger table, Unicode, which numbers the characters of nearly every writing system in use.
A Python str is a sequence of Unicode characters, so it holds text in other languages too, and len counts its characters: len('日本') is 2, and ord('é') is 233.
Every problem in this lesson limits its strings to ASCII letters and digits, so there one character is one char in C++ and one element of a str in Python.
Changing one character of a string
The programs so far read strings or built new ones. Sometimes you want to change one character of a string you already have: to capitalize a name, konjac should become Konjac. With a list you would assign to the index, the way nums[1] = 5 replaces one element of a list. Here is the same assignment on a string.
Assigning to one character
s = 'konjac'
s[0] = 'K'
print(s)Python stops with TypeError: 'str' object does not support item assignment. A str is immutable: once made, its characters never change. Assigning to an index works on a list, as nums[1] did, but a string rejects it.
The swap program's t + '1' made a new string for the same reason: a str cannot grow.
Capitalizing the first letter
Since the string cannot change, capitalizing makes a new string: the first character in uppercase, followed by every character after it.
s = input()
print(s[0].upper() + s[1:])Python details
s[1:] is the slice from index 1 to the end. 'k'.upper() returns 'K', and on a letter that is already uppercase it returns the same letter.
The Codeforces problem Word Capitalization asks for this program, and its first sample checks that the rest of the word is left alone.
Capitalize a word: make its first letter uppercase and leave every other letter exactly as it is. Print the result.
Constraints
- The word is not empty and has at most English letters, uppercase or lowercase
Sample 1 · Input
ApPLe
Output
ApPLe
Sample 2 · Input
konjac
Output
Konjac
On ApPLe, the program uppercases A, which is already uppercase, and keeps pPLe as it was, so it prints ApPLe. A program that uppercased the whole word would print APPLE and fail that sample.
'ApPLe'.capitalize() looks like a shortcut, but it also lowercases the rest of the word and returns 'Apple', which fails the first sample. Every string method that seems to change a string, such as upper, lower or replace, returns a new string and leaves the old one alone. s.upper() on its own line does nothing visible; s = s.upper() keeps the result. CAPS LOCK asks for the whole string in uppercase, which is one call to upper.
Deeper read: the cost of building a string one character at a time
The swap program built t with t = t + c. Because a Python string cannot change, each step can copy the whole of t into a new string. Building a string of characters then copies characters in total, which for is
A computer copies tens of billions of characters a second, and this many copies still take seconds: on an Apple M5 Pro, the loop took about 9 seconds with Python 3.14. Python can sometimes skip the copy and grow the string in place; in our runs it did so when the loop sat inside a function, where it took 0.05 seconds. It did not at the top level of a script, where this lesson's programs run, so do not count on it.
The safe habit is to collect the pieces in a list and join them once at the end. ''.join(parts) joins the strings in parts with nothing between them and copies each character once; built this way, a million characters took 0.04 seconds.
s = '1011'
parts = []
for c in s:
if c == '0':
parts.append('1')
else:
parts.append('0')
print(''.join(parts))Common mistakes
Joining a string and a number with
+in Python, as inw[0] + len(w) - 2.- Where it breaks
- On
localization, Python stops withTypeError: can only concatenate str (not "int") to str. - The fix
- Turn the number into a string first:
w[0] + str(len(w) - 2) + w[-1]printsl10n.
Comparing a C++
charwith a double-quoted string, as inif (c == "0").- Where it breaks
"0"is a string andcis a single character, so the compiler rejects the comparison.- The fix
- Use single quotes for one character:
c == '0'.
Asking whether
tappears inswith the C++ testif (s.find(t)).- Where it breaks
- When
tis at the very start,findreturns 0, which counts as false; whentis missing, it returnsstring::npos, a huge number, which counts as true. The test gives the wrong answer in exactly these two cases; it is right only whentis found past index 0. - The fix
- Compare with
npos:if (s.find(t) != string::npos).
Reading a line with
getline(cin, line)straight aftercin >> nin C++.- Where it breaks
- For the input
3followed byhello worldon the next line,linecomes back empty.cin >> nstops right after the 3 and leaves that line's line break unread, sogetlinereads the empty rest of the first line. - The fix
- Skip the rest of the number's line with
cin.ignore(numeric_limits<streamsize>::max(), '\n');(from<limits>) before the firstgetline, or callgetlineonce more and discard the result. A plaincin.ignore();skips only one character, so a space after the number still leaves the line break behind.
Recall Why does Way Too Long Words print the length minus 2 and not the length?
The number counts only the letters between the first and the last. Those two letters are written out, so they are left out of the count: localization has 12 letters and becomes l10n.
Recall After `t = t + '1'` in Python, is `t` the same string as before with one more character?
No. A Python string cannot change, so t + '1' makes a new string and the name t moves to it. In C++, t += '1' changes the string t already holds.
Key terms
| Term | Meaning |
|---|---|
| string | An ordered sequence of characters: 'hello' in Python, string s = "hello" in C++. |
| character | One letter, digit, space or symbol in a string. |
| char | C++'s type for one character, written in single quotes: 'h'. |
| character code | The number a character is stored as: a is 97, A is 65. |
| immutable | Cannot be changed after it is made, like a Python str. |
| mutable | Can be changed in place, like a C++ string. |
| slice | A new string made from part of another, in Python: s[1:]. |
| substring | A run of consecutive characters inside a string: nation in internationalization. |
| string literal | A string written directly in a program: 'hello' or "hello". |
| escape sequence | A backslash and a letter standing for one character that cannot be typed directly, such as \n for a newline. |
| concatenation | The string made by joining two strings end to end with +. |
| f-string | A Python string literal with f in front, whose {...} parts are replaced by the values of the expressions inside. |
