The Python posts on this page are based on what I learned from the book Jump to Python, interpreted and organized in my own way. If you find any mistakes or inaccuracies, please feel free to let me know, I’ll review and correct them as soon as possible.
Strings are one of the most fundamental yet powerful data types in Python.
In this chapter, we’ll explore how to create, manipulate, and format strings, and finish with a look at the most useful built-in string methods.
1. How to Create and Use Strings
In Python, a string (str) is an ordered sequence of characters.
It is immutable, meaning that once created, its content cannot be directly changed, any modification creates a new string object.
You can create strings using either single quotes (' ') or double quotes (" ").
Both forms behave exactly the same.
a = 'Hello Python'
b = "Hello Python"
print(a == b) # True
Python
복사
Because strings can contain either kind of quote. For example, the string "I'm fine" must use double quotes because it contains a single quote.
Multi-line Strings (Triple Quotes)
Triple quotes (""" """ or ''' ''') allow you to define multi-line strings.
They automatically include line breaks without the need for \n.
text = """This is
a multi-line
string."""
print(text)
Python
복사
This is
a multi-line
string.
Plain Text
복사
Triple-quoted strings are often used for docstrings, descriptions placed inside functions and classes.
def greet():
"""This function prints a greeting message."""
print("Hello")
Python
복사
Including Quotes Inside Strings
When you want to include quotes inside a string, you can use three approaches.
Single quotes containing double quotes
a = 'He said, "Hello!"'
Python
복사
Double quotes containing single quotes
b = "I'm happy"
Python
복사
Escaping quotes with a backslash (\)
c = 'He said, \"I\'m happy.\"'
print(c)
Python
복사
a = 'I'm fine' # ❌ SyntaxError
Python
복사
Use "I'm fine" or 'I\'m fine' instead.
Code | Meaning |
\n | Newline |
\t | Tab |
\\ | Backslash itself |
\' | Single quote |
\" | Double quote |
3. Assigning Multi-line Strings to Variables
You can represent multiple lines of text in two ways.
Using the newline character \n
multiline = "Hello\nPython\nWorld"
print(multiline)
Python
복사
Hello
Python
World
Plain Text
복사
Using triple quotes
multiline = """Hello
Python
World"""
print(multiline)
Python
복사
The result is the same, but triple quotes are more convenient when writing long text blocks such as SQL queries or HTML templates.
4. String Operations
Strings can be combined or repeated using operators like + and *.
These operations always create new strings, the original ones are never modified.
Concatenation
a = "Python"
b = "is fun"
print(a + " " + b)
Python
복사
Repetition
print("Hi! " * 3)
Python
복사
print("=" * 40)
print("LOG START")
print("=" * 40)
Python
복사
5. Finding the Length of a String
Use the built-in len() function to get the number of characters in a string.
a = "Python"
print(len(a)) # 6
Python
복사
Whitespace ( ), tabs (\t), and newline characters (\n) all count toward the length.
6. String Indexing and Slicing
Strings are sequences, so you can access individual characters by indexing and extract sub-strings by slicing.
Indexing
Each character in a string has an index number. Counting starts at 0 from the left, and at -1 from the right.
a = "Python"
print(a[0]) # P
print(a[-1]) # n
Python
복사
Strings are immutable — you can’t do a[0] = 'p'. Instead, build a new one
a = "Python"
a = "p" + a[1:]
Python
복사
Slicing
Slicing extracts a substring from a larger string.
The general syntax is…
string[start:end:step]
Plain Text
복사
•
start → the index to begin (inclusive)
•
end → the index to stop (exclusive, end-1 is the last included)
•
step → the step size (default : 1)
s = "Python Programming"
print(s[0:6]) # Python
print(s[7:18]) # Programming
print(s[:6]) # same as s[0:6]
print(s[7:]) # from 7 to the end
print(s[::2]) # every 2nd character
Python
복사
To reverse a string, use a negative step
print(s[::-1]) # gnimmargorP nohtyP
Python
복사
The end index is exclusive, meaning it is not included.
This rule allows expressions like [:n] + [n:] = full string to work perfectly in Python.
7. What is String Formatting?
String formatting allows you to insert variables and values into text dynamically.
Instead of concatenating strings manually, you can use placeholders to make output more flexible and readable.
print("I ate %d apples." % 3)
Python
복사
8. Old-Style String Formatting (%)
This method comes from the C programming language and is still supported in Python.
8.1 Substituting numbers and strings
num = 3
fruit = "apples"
print("I ate %d %s." % (num, fruit))
Python
복사
8.2 Alignment and spacing
print("%10s" % "hi") # right-aligned
print("%-10sjane" % "hi") # left-aligned
Python
복사
8.3 Floating-point precision
print("%0.4f" % 3.141592) # 3.1416
Python
복사
This style is considered legacy, modern code should use format() or f-strings.
9. Common Format Codes
Code | Meaning |
%s | String |
%d | Integer |
%f | Float |
%c | Character |
%% | Prints a literal % |
10. Combining Format Codes and Numbers
Alignment
print("%10s" % "Python") # right-aligned
print("%-10s!" % "Python") # left-aligned
Python
복사
Decimal places
print("%0.2f" % 3.14159)
Python
복사
11. Formatting with the format() Function
The format() method introduced in Python 3 is more powerful and readable than % formatting.
Basic usage
name = "Tom"
age = 25
print("My name is {0} and I’m {1} years old.".format(name, age))
Python
복사
Keyword arguments
print("I ate {num} apples.".format(num=5))
Python
복사
Alignment and padding
print("{0:<10}".format("left"))
print("{0:>10}".format("right"))
print("{0:^10}".format("center"))
print("{0:=^10}".format("hi"))
Python
복사
Decimal precision
print("{0:0.2f}".format(3.14159))
Python
복사
Printing braces
print("{{Python}}".format()) # {Python}
Python
복사
12. f-Strings (Python 3.6+)
f-strings are the most modern and convenient way to format strings.
Prefix a string with f and use {} to directly insert variables or expressions.
name = "Hyunwoo"
age = 30
print(f"My name is {name}, and I’m {age} years old.")
print(f"Next year, I’ll be {age + 1}.")
Python
복사
•
Easier to read and write
•
Faster than format()
•
Can evaluate expressions inline
x = 3.14159
print(f"PI = {x:.2f}") # 3.14
Python
복사
13. Useful String Methods
The str class provides a variety of built-in methods for processing and transforming strings.
Method | Description |
count() | Count occurrences of a substring |
find() | Return index of substring (or -1 if not found) |
index() | Same as find() but raises an error if not found |
join() | Concatenate elements with a separator |
upper() / lower() | Convert to upper/lowercase |
strip() / lstrip() / rstrip() | Remove whitespace |
replace() | Replace substrings |
split() | Split into a list |
isalpha() / isdigit() | Check if all characters are alphabetic/numeric |
startswith() / endswith() | Check prefix/suffix |
Examples
a = " Life is short "
print(a.strip()) # 'Life is short'
print(a.replace("short", "long")) # ' Life is long '
print(",".join(['a', 'b', 'c'])) # 'a,b,c'
print("PYTHON".lower()) # 'python'
print("python".upper()) # 'PYTHON'
Python
복사
These functions are essential for log parsing, CSV cleaning, and text preprocessing.



