Making strings: quotes and escapes
🌍 In real life. Everything you type in a text message is text: letters, digits, spaces, emoji, Bangla. Even a phone number in your contacts, like 01712-345678, is kept as text. You never add two phone numbers together; you only store them, show them and search them.
In Python, text is called a string, and it's one of the types you'll use most.
The idea in one sentence: a string (str) is a piece of text wrapped in quotes, and Python keeps exactly the characters between the quotes.
Its words:
- character: one letter, digit, space or symbol
- string: a row of characters in quotes,
"double"or'single' - escape: a backslash
\that changes what the next character means - length: how many characters a string has, given by
len()
Step by step, for print('She said "hi"'):
- Python sees the opening
'and starts collecting characters. - The
"marks inside aren't the same kind of quote, so they're just characters. - The next
'ends the string, andprintshows: She said "hi"
Digits in quotes are text too. Watch how quotes change the type:
print("Hello")
print('Hello')
print("আমি পাইথন শিখছি")How Python reads quotes. A string ends at the next quote of the same kind it started with. So to put a quote mark inside your text, either wrap the string in the other kind of quote, or escape the quote with a backslash.
print("It's sunny")
print('She said "hi"')Or use an escape: a backslash \ changes what the next character means.
\"or\'is a quote that doesn't end the string\nstarts a new line\tis a tab (a wide space)\\is one real backslash
print("Line one\nLine two")
print("Name:\tRimi")
print("C:\\Users\\rimi")
print('It\'s fine')+ joins two strings, * repeats one, and len() counts the characters.
first = "Py"
second = "thon"
print(first + second)
print("ha" * 3)
print(len("hello"))Triple quotes (""") let a string run over several lines:
poem = """Roses are red,
Python is fun."""
print(poem)Mistakes and edge cases.
- The same quote inside and outside.
print('It's sunny')givesSyntaxError: unterminated string literal: the'in It's ends the string early. Use"It's sunny". - Joining text and a number.
"Hi" + 5givesTypeError: can only concatenate str (not "int") to str. - Backslashes in paths. In
"C:\new", the\nbecomes a new line. Write\\for one real backslash. - Repeating by a decimal.
"ha" * 2.5givesTypeError: can't multiply sequence by non-int of type 'float'. - Spaces count.
len("hi there")is 8: the space is a character too.
Quiz
What does this print?
print("ab" + "cd")What does this print?
print("-" * 5)What does this print?
print(len("cat"))What does this print?
print("A\nB")Which line causes an error?
print("Good morning") print('It's late')What is the type of
"3.5"?- float
- str
- int
Coding tasks
Print exactly this:
She said "hi"Using one
print(), show two lines:Hello WorldUse
\n.wordholds"na". Makesonghold"nananana batman", usingwordwith*and+.