-8

I'm new to Tkinter and I'm working on a text editor. I want to implement a find text feature in my code and I recently came across a line of code that I don't quite understand. I would like to understand what that line of code does. This is the line of code:

'{}+{}c'.format(start_pos, len(needle))
ruohola
  • 21,987
  • 6
  • 62
  • 97
konnichiwa
  • 50
  • 6
  • 5
    The first `{}` will be replaced by `start_pos`. The second will be replaced by `len(needle)`. This is like every other usage of [the `format` method](https://docs.python.org/3/library/stdtypes.html#str.format). – khelwood Aug 09 '19 at 13:19

4 Answers4

1

It will make a new string where the arguments of format() are placed in place of the {}:

start_pos = 1
needle = [1, 2, 3]

print('{}+{}c'.format(start_pos, len(needle)))

Output:

1+3c

The best place to look-up stuff like this is definitely the Python docs.

I would personally search for this with the Google search:

site:https://docs.python.org/ format

then select the top link and do Ctrl+F for format() on the page.

Using this technique will bring us here: https://docs.python.org/3/library/stdtypes.html#str.format

ruohola
  • 21,987
  • 6
  • 62
  • 97
0

format will replace each {}.

So here, the code is the same as :

str(start_pos) + '+' + str(len(needle)) + 'c'
Alex_6
  • 259
  • 4
  • 16
0

See String.format()

It takes arguments in the function and inserts them within the curly brackets of the string.

so: '{}+{}c'.format(start_pos, len(needle))

Adds the two variables start_pos and len(needle) into the string replacing the curly brackets.

{start_pos}+{len(needle)}

Josh Sharkey
  • 1,008
  • 9
  • 34
0

I'll break it down for you.

You have a string, '{}+{}c'. In Tkinter, when searching for words, you usually find the position of the first letter, and the last letter. To find the position of the last letter of the word, you need to find the length of the word, and add that to the starting position.

For example, say you have the word 'hello'. For simplicity, we'll assume to the position of the first letter, 'h', is 1.0.

But we need to also know the position of the last letter, 'o'. To do this, we get the length of 'hello', which is 5 characters, and add it to the start position, which is 1.0.

1.0 + 5 characters (0.5) = 1.5

So, we now know the position of the last letter. But how do we tell Tkinter this? Well, we use '+xc', where x is any number, and c means characters. In the case of 'hello', 'hello' is 5 characters long, so we would write '+5c'

In your example, the code uses format(). Format is a way to easily use variables with strings. Your code takes start_pos, the position of the first letter, and the length of the word, len(needle), and passes that into format().

This then replaces the first instance of '{}' with start_pos, and the second instance with len(needle). This is like writing start_pos + '+' + len(needle) + 'c'

jack.py
  • 362
  • 8
  • 23