Code Golf Challenge
Given a string of 10 characters:
'abcdefghij'
I want to format it in this pattern and print it in the console in a minimum number of characters:
(abc) def-ghij
My solution:
print(f"({s[0:3]}) {s[3:6]}-{s[6::]}")
print(f"({s:.3}) {s[3:6]}-{s[6:]}")
Uses the solution from the question but saves three bytes:
: in the final slice s[6::], andprecision specifier (.) of the format_spec (the bit after the : in {...:...}) which is overloaded for string types to give a prefix so {s[0:3]} -> {s[:3]} -> {s:.3}slightly improved version of your f-string (see also Jonathan Allan's comment), wrapped in a function
print(f"({s[:3]}) {s[3:6]}-{s[6:]}")
without format strings
print("("+s[:3]+")",s[3:6]+"-"+s[6:])
uses that print inserts a space between arguments
C-style format string
print("(%s%s%s) %s%s%s-%s%s%s%s"%(*s,))
printing characters separately is slightly shorter than spiting string in 3 parts
"($($a[0..2])) $($a[3..5])-$($a[6..9])"-join''
The output is a little weird, if someone can suggest a fix to that it would be much appreciated!
print"("+s[:3]+")",s[3:6]+"-"+s[6:]
Simply reduces the second solution of this answer by 2 bytes, since in Python 2 print would be a statement, not a function.
[tips]as it is no longer relevant with your new question. \$\endgroup\$