xSKILLby Infirals
Register

Python for Beginners

0 of 24 notes read 0%

Reading progress is saved to your INFIRALS account. Sign in to keep this note marked as read.

Strings

Basics8 min readLesson 4 of 8

A string is a sequence of characters, written between single or double quotes. Both quote styles do the same job, so choose one and stay consistent inside a line. Strings can hold letters, digits, spaces, punctuation, or no characters at all. Characters in a string cannot be changed in place, but a name can be rebound to a new string. Names, messages, and file contents arrive as text, so string handling appears in most programs.

python
name = 'Maya'
greeting = 'Hello, ' + name
print(greeting)
print(name[0])
print(len(name))

Output

Hello, Maya
M
4

4.1 Indexing and slicing

Indexing counts from zero, so word[0] is the first character and word[-1] is the last. A slice such as word[1:4] includes the start index and stops before the end index. Slicing past the end is safer than indexing past the end: s[0:100] returns the available characters, while s[100] raises IndexError.

4.2 Joining and formatting

  • + joins two strings.
  • * repeats a string: 'ha' * 3 gives 'hahaha'.
  • upper(), lower(), and strip() return a new string.

An f-string such as f'Total: {amount}' converts values for display while keeping the sentence readable.

python
item = 'notebook'
price = 45
label = f'{item}: {price} rupees'
print(label)
print(label.upper())

Output

notebook: 45 rupees
NOTEBOOK: 45 RUPEES

4.3 Common mistake

Joining text and a number with + fails. The expression 'Age: ' + 15 raises TypeError because the left side expects another string. Use an f-string or str(15) to make the number part of the text before joining.

python
word = 'python'
print(word[0:3])
print(word[-3:])
print(word * 2)
print(word.upper())

Output

pyt
hon
pythonpython
PYTHON

4.4 Practice

  1. Store your full name with extra spaces around it.
  2. Print the cleaned name and its length, then print the first three characters.
  3. Add an f-string that prints the name and your age in a sentence.

If you need literal quote marks inside a string, use the other quote type on the outside or escape them with a backslash.

Interview questions

3 questions from this note. Open one to see the answer; no account needed.

  • 01Why does `'Age: ' + 15` fail?

    The `+` operator joins two strings, and `15` is an integer. Convert it with `str(15)` or place it in an f-string first.

  • 02What is the result of `'abc'[1]`?

    It is `'b'`, because string indexes start at `0`.

  • 03Do string methods like `upper()` change the original string?

    No. They return a new string, so you need to store or print the returned value to use the changed text.