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.
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:
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:
1print("C:\new") # prints C: and then "ew" on a new line
2print(r"C:\new") # Console: C:\newCalling str() on any object gives its string form: str(1337) is '1337'.
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:
1s = "flag{example}"
2s[0] # Return: 'f'
3s[-1] # Return: '}'
4sThe 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:
s = "F" + s[1:] # s = "Flag{example}"The in operator checks for a substring anywhere in the string:
"example" in s # Return: TrueString methods never change the original string. Each returns a new string (or a list, or a number), which you have to keep:
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.
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:
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.
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:
1", ".join(["22", "80", "443"]) # Return: '22, 80, 443'
2"".join(["f", "l"join() only accepts strings. To join numbers, convert them first: " ".join(str(n) for n in nums).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:
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():
"flag{a}".removeprefix("flag{").removesuffix("}") # Return: 'a'replace(old, new) swaps every occurrence of a substring:
"a-b-c".replace("-", "") # Return: 'abc'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:
1s = "the cat sat"
2s.find("at") # Return: 5
3s.find("dog") # Return: -1
4startswith() and endswith() check the ends of a string, and accept a tuple to check several options at once:
1"flag{x}".startswith("flag{") # Return: True
2"exploit.py".endswith((".py", ".sh")) # Return: Trueupper(), 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:
1"1337".isdigit() # Return: True
2"-5".isdigit() # Return: False, '-' is not a digit
3"abc".isalpha()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.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:
1line = "10.0.0.5:8080 open http\n"
2
3addr, state, service = line.split() # ['10.0.0.5:8080', 'open', 'http']
4The 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:
a, b, c = map(int, "3 14 15".split()) # a = 3, b = 14, c = 15When a line's shape is irregular, regular expressions take over where split() runs out.
An f-string has an f before the opening quote, and any expression inside curly braces is evaluated and inserted into the string:
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:
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.
After the expression, a colon starts a format specifier that controls how the value is shown. The ones you'll use most:
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.
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:
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.
"%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.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:
1ord("A") # Return: 65
2chr(97) # Return: 'a'
3ord("€") # Return: 8364Moving 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:
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.
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:
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.