Jump to content

Strings and Numbers

From Slow Like Wiki
Revision as of 15:00, 3 April 2024 by Rob (talk | contribs) (Created page with "== Strings == <syntaxhighlight lang="python" line> my_empty_string = "" my_string = "Hello" print(my_string) </syntaxhighlight> Set string to title, lower, or uppercase <syntaxhighlight lang="python" line> full_name = "bob smith" print(full_name.title()) # also .lower(), .upper() </syntaxhighlight> Remove whitespace or text from beginning or end <syntaxhighlight lang="python" line> my_spacey_string = " Hello " print(my_spacey_string.strip()) # also .lstrip() and .str...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Strings


my_empty_string = ""
my_string = "Hello"
print(my_string)

Set string to title, lower, or uppercase


full_name = "bob smith"
print(full_name.title()) # also .lower(), .upper()

Remove whitespace or text from beginning or end


my_spacey_string = "   Hello "
print(my_spacey_string.strip()) # also .lstrip() and .strip()
my_url = "http://www.acme.com"
print(my_url.removeprefix('https://')) # also removesuffix

Use f-strings to insert variables into strings


my_name = "bob"
print(f"Hello, {my_name.title()}!")

Numbers


my_number = 8
print(my_number)

2 + 3                    # add
3 - 2                    # subtract
2 * 3                    # multiply
3 / 2                    # divide
(2+3)*4                  # set priority with brackets
3 % 2                    # modulo - output the remainder after division
 
3 ** 2                   # 3-squared
3 ** 3                   # 3-cubed
10 ** 6                  # 10 to the power of 6

10_000_000               # use underscores to make numbers more legible

MAX_CONNECTIONS = 5_000  # use all-caps to indicate constants

X, y, z = 0, 0, 0        # To initialize multiple variables in one line, use commas: