Table of Contents
IronForgeCyber
Courses
Resources
Blog
Log In


IronForgeCyber

AboutPrivacyTerms

© 2026 IronForgeCyber. All rights reserved.

  1. courses
  2. python
  3. strings
9 min read

Strings

Most challenge input arrives as text, and most of the work of parsing it is string handling: splitting a line into fields, stripping whitespace, and turning pieces into numbers. Python's str type holds a sequence of Unicode characters. It is immutable, and it comes with a large set of methods that make this kind of work quick, along with f-strings for building output.

Creating Strings

Strings are written in single, double or triple quotes, as covered in Basic Syntax. Inside a string, a backslash starts an escape sequence for characters you can't type directly:

python
1"line one\nline two"     # \n is a newline
2"col1\tcol2"             # \t is a tab
3"it's \"quoted\""        # \" is a literal double quote
4"C:\\Users"              # \\ is a literal backslash

Putting an r in front makes a raw string, where backslashes are kept exactly as written. Raw strings are what you want for regular expressions and Windows paths:

python
1print("C:\new")     # prints C: and then "ew" on a new line
2print(r"C:\new")    # Console: C:\new

Calling str() on any object gives its string form: str(1337) is '1337'.

Indexing and Slicing

A string is a sequence of characters, so it supports the same indexing and slicing as a list. Indexes start at 0, and negative indexes count back from the end:

python
1s = "flag{example}"
2s[0]         # Return: 'f'
3s[-1]        # Return: '}'
4s

The full slicing rules are in List Slicing. Python has no separate character type: indexing a string gives back another string, one character long.

Strings are immutable, so you can't change a character in place. s[0] = "F" raises a TypeError. Instead, build a new string from pieces and assign it:

python
s = "F" + s[1:]    # s = "Flag{example}"

The in operator checks for a substring anywhere in the string:

python
"example" in s     # Return: True

Common Methods

String methods never change the original string. Each returns a new string (or a list, or a number), which you have to keep:

python
1name = "  echo  "
2name.strip()        # returns "echo", but name is unchanged
3name = name.strip() # now name = "echo"

Forgetting to assign the result is one of the most common beginner bugs.

Splitting and Joining

split() breaks a string into a list of pieces. With no argument, it splits on any run of whitespace and ignores whitespace at either end, which is almost always what you want for parsing input. With an argument, it splits on exactly that separator:

python
1"  10   20 30\n".split()       # Return: ['10', '20', '30']
2"a,b,,c".split(",")            # Return: ['a', 'b', '', 'c']
3"key=value=x".split(

The second argument, maxsplit, limits how many splits are made, which is handy when only the first separator matters. splitlines() splits on line endings, and partition(sep) splits once into exactly three parts: the part before, the separator, and the part after.

python
1"one\ntwo\nthree".splitlines()       # Return: ['one', 'two', 'three']
2"user:echo".partition(":")           # Return: ('user', ':', 'echo')

join() goes the other way. It's called on the separator, and takes a list of strings to glue together:

python
1", ".join(["22", "80", "443"])    # Return: '22, 80, 443'
2"".join(["f", "l"
Warning
join() only accepts strings. To join numbers, convert them first: " ".join(str(n) for n in nums).

Cleaning Up

strip() removes whitespace from both ends of a string, and lstrip() and rstrip() remove it from only the left or right. Each can also take a string of characters to remove instead:

python
1"  hello\n".strip()       # Return: 'hello'
2"xxhixx".strip("x")       # Return: 'hi'
3"0042".lstrip("0"

The argument is a set of characters, not a prefix: "flag{a}".strip("flag{}") strips every f, l, a, g, { and } from both ends, and returns an empty string. To remove an exact prefix or suffix, use removeprefix() and removesuffix():

python
"flag{a}".removeprefix("flag{").removesuffix("}")    # Return: 'a'

replace(old, new) swaps every occurrence of a substring:

python
"a-b-c".replace("-", "")     # Return: 'abc'

Searching

find() returns the index of the first occurrence of a substring, or -1 if there is none. index() does the same but raises a ValueError when the substring is missing. count() counts non-overlapping occurrences:

python
1s = "the cat sat"
2s.find("at")          # Return: 5
3s.find("dog")         # Return: -1
4

startswith() and endswith() check the ends of a string, and accept a tuple to check several options at once:

python
1"flag{x}".startswith("flag{")             # Return: True
2"exploit.py".endswith((".py", ".sh"))     # Return: True

Case and Content Checks

upper(), lower(), title() and swapcase() change case. Comparing two strings case-insensitively is usually done by lowering both: a.lower() == b.lower().

A family of is methods check what a string contains, returning True only if the string is non-empty and every character qualifies:

python
1"1337".isdigit()      # Return: True
2"-5".isdigit()        # Return: False, '-' is not a digit
3"abc".isalpha()
Tip
Because isdigit() rejects negative numbers and decimals, the reliable way to check whether a string is a number is to try converting it with int() or float() and catch the ValueError, as covered in Exceptions.

Parsing Input

Most challenge input is lines of text with a fixed shape. Putting the methods above together, here is a line from a made-up port scan log, taken apart into typed values:

python
1line = "10.0.0.5:8080 open http\n"
2
3addr, state, service = line.split()      # ['10.0.0.5:8080', 'open', 'http']
4

The pattern is always the same: split the line into fields, split fields further where needed, and convert each piece to the type it really is. map(int, ...) converts every piece at once, which pairs well with unpacking:

python
a, b, c = map(int, "3 14 15".split())    # a = 3, b = 14, c = 15

When a line's shape is irregular, regular expressions take over where split() runs out.

Formatting Output

f-strings

An f-string has an f before the opening quote, and any expression inside curly braces is evaluated and inserted into the string:

python
1host, port = "10.0.0.5", 8080
2f"connecting to {host}:{port}"         # Return: 'connecting to 10.0.0.5:8080'

Adding = after the expression prints the expression itself too, which is a quick way to debug:

python
f"{port=}"         # Return: 'port=8080'

To put a literal brace in an f-string, double it: f"flag{{{name}}}" gives flag{...} around the value of name.

Format Specifiers

After the expression, a colon starts a format specifier that controls how the value is shown. The ones you'll use most:

python
1n = 255
2f"{n:x}"        # Return: 'ff', hexadecimal
3f"

Specifiers like :08b and :#x are worth memorizing: dumping values in binary and hex is constant work in reverse engineering and exploitation.

str versus repr

Every object has two string forms. str() is the friendly one, meant for display. repr() is the unambiguous one, meant for debugging, and for strings it includes the quotes and shows escape sequences. In an f-string, !r asks for the repr:

python
1s = "tab\there"
2print(s)              # Console: tab	here
3print(repr(s))        # Console: 'tab\there'

When a string isn't matching what you expect, print its repr. Hidden whitespace, such as a trailing \n from reading a file, shows up immediately.

Older formatting styles
You'll meet two older styles in existing code and exploit scripts: "%s:%d" % (host, port), borrowed from C's printf, and "{}:{}".format(host, port). Both still work, but f-strings are shorter and easier to read for new code.

Characters and Code Points

Every character has a number, its code point in Unicode. ord() gives a character's code point, and chr() turns a code point back into a character. For plain English text these are the same numbers as ASCII:

python
1ord("A")       # Return: 65
2chr(97)        # Return: 'a'
3ord("€")       # Return: 8364

Moving between characters and numbers is the basis of classic ciphers. A Caesar cipher shifts every letter a fixed distance through the alphabet, wrapping around at the end:

python
1def caesar(text, shift):
2    out = []
3    for ch in text:

A string's length counts characters, not bytes. len("é") is 1, even though storing it in UTF-8 takes two bytes. That difference between characters and their raw bytes is what Bytes & Encoding is about.

Building Strings Efficiently

Because strings are immutable, s += piece creates a whole new string every time. In a loop over a large input, that copying adds up. The idiomatic approach is to collect the pieces in a list and join them once at the end, as the caesar function above does:

python
1parts = []
2for i in range(5):
3    parts.append(str(i))

For a handful of pieces, + and f-strings are perfectly fine. Reach for join() when you're building a string inside a loop.

5"\x41" # \x41 is the character with code 0x41: 'A'
[
5
:
-
1
]
# Return: 'example'
5s[::-1] # Return: '}elpmaxe{galf'
6len(s) # Return: 13
"="
,
1
)
# Return: ['key', 'value=x']
,
"a"
,
"g"
]
)
# Return: 'flag'
)
# Return: '42'
s
.
count
(
"at"
)
# Return: 2
# Return: True
4"abc123".isalnum() # Return: True
5" ".isspace() # Return: True
host
,
port
=
addr
.
split
(
":"
)
# host = '10.0.0.5', port = '8080'
5port = int(port) # port = 8080
6octets = [int(o) for o in host.split(".")] # octets = [10, 0, 0, 5]
3f"next port is {port + 1}" # Return: 'next port is 8081'
{
n
:
#x
}
"
# Return: '0xff', with the 0x prefix
4f"{n:08b}" # Return: '11111111', binary padded to 8 digits
5f"{n:04x}" # Return: '00ff', hex padded with zeros to 4 digits
6f"{n:>6}" # Return: ' 255', right-aligned in 6 characters
7f"{n:<6}|" # Return: '255 |', left-aligned
8f"{3.14159:.2f}" # Return: '3.14', two decimal places
9f"{1234567:,}" # Return: '1,234,567', thousands separators
4f"got {s!r}" # Return: "got 'tab\\there'"
4 if "a" <= ch <= "z":
5 out.append(chr((ord(ch) - ord("a") + shift) % 26 + ord("a")))
6 else:
7 out.append(ch)
8 return "".join(out)
9
10caesar("flag{rot}", 13) # Return: 'synt{ebg}'
11caesar("synt{ebg}", 13) # Return: 'flag{rot}'
4"".join(parts) # Return: '01234'