Skip to content

Strings as immutable sequences [ref]

Problem

  • Concatenate "ab" and "cd"; join ["c", "a", "t"] without a separator.
  • Split "name@example.com" at the first "@"; split "foo+bar+baz" at only its first "+".
  • Remove periods from "a.b.c" and count zeroes in "0010".
  • Lowercase "A" and test whether "A", "7", and "!" are alphanumeric.
  • Convert "7" to its decimal digit using ord; convert the code point for "a" back to a character.
  • Build an address from local = "user" and domain = "example.com" with an f-string.
  • Test whether "cab" contains "ab" and whether "abc" starts with "ab".

Python solution

"ab" + "cd"                  # 'abcd'
"".join(["c", "a", "t"])       # 'cat'

"name@example.com".split("@", 1)  # ['name', 'example.com']
"foo+bar+baz".split("+", 1)       # ['foo', 'bar+baz']

"a.b.c".replace(".", "")  # 'abc'
"0010".count("0")          # 3

"A".lower()  # 'a'
("A".isalnum(), "7".isalnum(), "!".isalnum())  # (True, True, False)

ord("7") - ord("0")  # 7
chr(ord("a"))        # 'a'

local, domain = "user", "example.com"
f"{local}@{domain}"  # 'user@example.com'

"ab" in "cab"           # True
"abc".startswith("ab")  # True