Live AI Powered DevOps with AWS
PythonStrings

Working with Strings


Strings represent text in Python. When you type something in the interpreter, Python attempts to understand whether it is a number, a variable name, or literal text. Anything intended to be treated as text must be enclosed in quotes — otherwise Python interprets it as a variable.

1. What Is a String?

A string is a sequence of characters enclosed in:

  • Single quotes'...'
  • Double quotes"..."
  • Triple quotes'''...''' or """...""" (for multi-line text)

Strings allow you to work with names, sentences, file paths, and any other form of textual data.

Strings in Python

Why Quotes Are Needed

If you enter text without quotes, Python assumes it is a variable:

>>> navin
NameError: name 'navin' is not defined

To treat it as a string:

>>> 'navin'
'navin'
>>> print('navin')
navin

The print() function displays only the content, without quotes.

Multi-Line Strings

Triple-quoted strings allow text across multiple lines:

msg = '''
This is a
multi-line string.
'''
print(msg)

Using quotes inside strings

Apostrophes inside strings

If a string contains ', use double quotes outside:

>>> print("navin's laptop")
navin's laptop

If you want the same type of quotes inside and outside, escape the inner one:

>>> print('navin\'s "laptop"')
navin's "laptop"

Incorrect quoting causes:

>>> print('navin's telusko')
SyntaxError: unterminated string literal

Escape Sequences in Strings

Python uses backslashes (\) for special characters:

  • \n → Newline
  • \t → Tab
  • \\ → Literal backslash

Example:

>>> print('Line1\nLine2')
Line1
Line2
>>> print('c:\\docs\navin')
c:\docs
avin

Avoiding accidental escape sequences

Windows file paths often cause errors:

>>> print('c:\users\navin')
SyntaxError: (unicode error)

Fix with double backslashes:

>>> print('c:\\users\\navin')
c:\users\navin

Raw Strings

Raw strings disable escape sequences and treat backslashes literally:

>>> print(r'c:\users\navin')
c:\users\navin

Raw strings cannot end with a single backslash: r"c:\path\" → ❌ invalid


String Operations

a) Concatenation (+)

>>> 'navin' + ' reddy'
'navin reddy'

Only strings can be concatenated:

>>> 'navin' + 5
TypeError

b) Repetition (*)

>>> 'navin ' * 3
'navin navin navin '

Summary

  • Strings represent text and must be enclosed in quotes.
  • Python errors occur when quotes are mismatched or missing.
  • Escape characters like \n and \\ control formatting.
  • Use raw strings (r'...') to avoid accidental escape processing.
  • Strings support operations such as concatenation and repetition.
  • Triple quotes allow easy creation of multi-line text blocks.

Written By: Muskan Garg

How is this guide?

Last updated on