String Types in Python with Examples
In Python, a string is a sequence of characters enclosed in quotes. Python supports various ways to define and manipulate strings. Strings are one of the most commonly used data types.
1. Single-line Strings
You can define strings using single (' '), double (" "), or **triple (''' ''' or """ """) quotes.
Examples:
s1 = 'Hello'
s2 = "World"
print(s1, s2) # Output: Hello World
Both s1
and s2
are simple single-line strings.
2. Multi-line Strings
Use triple quotes to define multi-line strings.
Example:
paragraph = """This is a
multi-line string
in Python."""
print(paragraph)
3. Raw Strings
Raw strings treat backslashes (\
) as literal characters. Prefix the string with r
or R
.
Example:
path = r"C:\Users\Name\Documents"
print(path) # Output: C:\Users\Name\Documents
Without r
, Python might interpret \n
as a newline.
4. Unicode Strings
In Python 3, all strings are Unicode by default, so you can include non-ASCII characters.
Example:
greeting = "नमस्ते"
emoji = "🙂"
print(greeting, emoji) # Output: नमस्ते 🙂
5. Formatted Strings (f-strings)
Introduced in Python 3.6, f-strings allow embedded expressions inside string literals, using {}
.
Example:
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
6. Byte Strings
Byte strings are sequences of bytes rather than characters. Prefix the string with b
.
Example:
byte_str = b"Hello"
print(byte_str) # Output: b'Hello'
print(type(byte_str)) # <class 'bytes'>
Useful when working with binary data or network programming.
Summary Table
Type |
Syntax Example |
Use Case |
Single-line |
'Hello' , "World" |
Regular short strings |
Multi-line |
'''Hello\nWorld''' |
Long text, paragraphs |
Raw string |
r"C:\path\file.txt" |
File paths, regex |
Unicode (default) |
"नमस्ते" |
Non-English languages |
f-string |
f"Hi {name}" |
String interpolation |
Byte string |
b"data" |
Binary files, network operations |