feat: string manipulation
This commit is contained in:
@@ -1,7 +1,65 @@
|
|||||||
def t_strings():
|
from string import Formatter
|
||||||
|
|
||||||
|
def template_strings():
|
||||||
my_template = "This is a value: {test}"
|
my_template = "This is a value: {test}"
|
||||||
print(my_template.format(test="another"))
|
print(my_template.format(test="another"))
|
||||||
|
|
||||||
|
complext_template = "The number of days in a %s is %d"
|
||||||
|
# % is the string formatting operator
|
||||||
|
print(complext_template % ("year", 365))
|
||||||
|
|
||||||
|
print("Numbers can also be formatted, such as %.2f" % 123.1235)
|
||||||
|
|
||||||
|
print("Simple template values can also be indexed {0} {1} but CANT use the formatting operator '%'".format("first", "second"))
|
||||||
|
|
||||||
|
print("What can do is specify both a template value name and a format, such as {test:.2f}".format(test=123.12345))
|
||||||
|
|
||||||
|
name = "Me"
|
||||||
|
surname = "Another dude"
|
||||||
|
print(f"I'm {name} {surname}")
|
||||||
|
|
||||||
|
# Lower level access to format flows
|
||||||
|
test_template = "This is an example with {with_quotes!r} or a number {num:.2f}"
|
||||||
|
for text, field, format_spec, conversion in Formatter().parse(test_template):
|
||||||
|
print(f"{text=}, {field=}, {format_spec=}, {conversion=}")
|
||||||
|
|
||||||
|
# Allow input in templates
|
||||||
|
# print(t"Hello, {input("Enter your name: ")} 👋 Welcome back!")
|
||||||
|
|
||||||
|
|
||||||
|
def split_strings():
|
||||||
|
example_string = "This is a long string with a number 2134"
|
||||||
|
print(f"> Example string: {example_string}")
|
||||||
|
|
||||||
|
first_four = example_string[:4]
|
||||||
|
print(f"> First four: {first_four}")
|
||||||
|
|
||||||
|
last_four = example_string[-4:]
|
||||||
|
print(f"> Last four: {last_four}")
|
||||||
|
|
||||||
|
without_first_four = example_string[4:]
|
||||||
|
print(f"> Without first four: {without_first_four}")
|
||||||
|
|
||||||
|
without_last_four = example_string[:-4]
|
||||||
|
print(f"> Without last four: {without_last_four}")
|
||||||
|
|
||||||
|
with_replaced_l = example_string.replace("l", "p")
|
||||||
|
print(f"> With replaced l: {with_replaced_l}")
|
||||||
|
|
||||||
|
# Must use ascii chars
|
||||||
|
with_multiple_removed = example_string.translate({97: None, 101: None, 105: None, 111: None, 117: None})
|
||||||
|
print(f"> Without vocals: {with_multiple_removed}")
|
||||||
|
|
||||||
|
a_to_o = str.maketrans("a", "o")
|
||||||
|
with_o_instead_of_a = example_string.translate(a_to_o)
|
||||||
|
print(f"> With o instead of a: {with_o_instead_of_a}")
|
||||||
|
|
||||||
|
no_a = str.maketrans("", "", "a")
|
||||||
|
without_a = example_string.translate(no_a)
|
||||||
|
print(f"> Without a: {without_a}")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def run():
|
def run():
|
||||||
t_strings()
|
template_strings()
|
||||||
|
split_strings()
|
||||||
|
|||||||
Reference in New Issue
Block a user