☰ خطة العام · تكنولوجيا المعلومات والاتصالات (بالإنجليزية)

Strings in Python

الأسبوع 6 · الدرس ٣ «السلاسل النصية والقوائم في لغة Python» (١): السلاسل النصية والطول والفهرس والحلقة والبحث · 3 دروس
1

Strings and their length

ICT Prep 3 Term 1, Unit 1, Lesson 3: pp. 32–34
GoalSay what a string is, write strings with quotation marks and find their length with len.
New words
string · text made of characters inside quotation markscharacter · one letter, digit, symbol or spacequotation marks · single ' ' or double " " marks around a stringlen() · gives the number of characters in a string
Explanation

A string is text. It is a row of characters inside quotation marks, single or double, as long as the two marks match. The characters can be letters, digits, symbols and spaces, not letters only. So "school", "2026" and "hi there!" are all strings. The function len() counts the characters: len("school") is 6. Spaces count too, so len("good day") is 8 and an empty string "" has length 0. Take care with digits inside quotation marks: "12" is text, not a number. Plus on two strings joins them, so "12" + "3" gives 123, while 12 + 3 gives 15. Remember Week 1, where the typed input was text until int() changed it.

StringCharacters insidelen
"Python"6 letters6
"a1!"a letter, a digit, a symbol3
"hi there"7 letters and 1 space8
"2026"4 digits4
Worked examples
Python
1word = "school"
2print(len(word))
3print(len("good day"))
4print(len(""))
Output
6
8
0
Mona asks Python for three lengths. The word school has 6 characters, good day has 8 because the space counts, and the empty string has none.
Python
1print("12" + "3")
2print(12 + 3)
Output
123
15
Quotation marks make the difference between text and numbers. The first line joins two texts. The second adds two numbers.
Class activity

Write three strings of your own: one with only letters, one with letters and digits, and one with a space and a symbol. Write the length of each, counting every character. Check one with a classmate.

Practice
1
What is len("notebook")?
2
Why is len("a b") equal to 3 and not 2?
3
What does "4" + "5" give, and what does 4 + 5 give?
4
Can a string hold digits and symbols, or only letters?