-2

I need to format a string with substrings of a variable. If I do:

sample="1234567890XXXX"
f"{sample[:5]}/{sample[5:10]}/{sample}/config"

It works fine:

'12345/67890/1234567890XXXX/config'

But if I use format:

"{sample[:5]}/{sample[5:10]}/{sample}/config".format(sample="1234567890XXXX")

I get an error:

TypeError: string indices must be integers, not 'str'

Any way to make it work with a format?

EDIT: just to clarify some things. The format string is passed through a command line argument and the format arguments automatically extracted from a pandas dataframe (as a dict). So, I do not thing the propsed solutions (f-strings and extra format arguments) will work.

args.out_path.format(**name)
3
  • 1
    Slice the strings and pass the slices as multiple arguments to format: "{s1}/{s2}/{sample}/config".format(sample="1234567890XXXX", s1={sample[:5]}, s2={sample[5:10]}) Commented Nov 20, 2023 at 14:26
  • What's wrong with using f-string, which is way more readble? Commented Nov 20, 2023 at 14:35
  • Because i want the format string to be passed as a command line argument, so I don't think the f-string will work. And neither will multiple arguments to format. Commented Nov 22, 2023 at 10:12

1 Answer 1

1

As @pho suggested you can supply the slices to str.format():

"{s1}/{s2}/{sample}/config".format(sample="1234567890XXXX", s1=sample[:5], s2=sample[5:10])

#output
'12345/67890/1234567890XXXX/config'

Python f-strings are very different from str.format() templates. Python f-strings support slicing and don't use a "mini-language" like the formatter. The full power of a python expression is available within each curly-brace of an f-string.

“Format specifications” are used within replacement fields contained within a format string to define how individual values are presented (see Format String Syntax and Formatted string literals). They can also be passed directly to the built-in format() function. Each formattable type may define how the format specification is to be interpreted.

https://docs.python.org/3/library/string.html#format-specification-mini-language


No, slicing is not supported by builtin str formatting. Although, there is a workaround in case f-strings (runtime evaluated) don't fit your needs.

You can use a run-time evaluated "f" string. Python f-strings support slicing and don't use a "mini-language" like the formatter.

https://stackoverflow.com/a/62024873/13086128

https://stackoverflow.com/a/49884004/13086128

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.