Strings and Numbers: Difference between revisions
Appearance
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..." |
No edit summary |
||
Line 6: | Line 6: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Present string in title, lower, or uppercase | |||
<syntaxhighlight lang="python" line> | <syntaxhighlight lang="python" line> | ||
full_name = "bob smith" | full_name = "bob smith" | ||
Line 47: | Line 47: | ||
X, y, z = 0, 0, 0 # To initialize multiple variables in one line, use commas: | X, y, z = 0, 0, 0 # To initialize multiple variables in one line, use commas: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
== Cast Variables to Specific Types == | |||
<syntaxhighlight lang="python" line> | <syntaxhighlight lang="python" line> | ||
my_number = "1". # As it is in quotes, set to a string | |||
x = int(my_number) # convert to an integer | |||
x = float(my_number) # convert to a float | |||
x = string(my_number) # convert to a string | |||
</syntaxhighlight> | </syntaxhighlight> |
Revision as of 15:09, 3 April 2024
Strings
my_empty_string = ""
my_string = "Hello"
print(my_string)
Present string in 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:
Cast Variables to Specific Types
my_number = "1". # As it is in quotes, set to a string
x = int(my_number) # convert to an integer
x = float(my_number) # convert to a float
x = string(my_number) # convert to a string