Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slicing strings in str.format

I want to achieve the following with str.format:

x,y = 1234,5678
print str(x)[2:] + str(y)[:2]

The only way I was able to do it was:

print '{0}{1}'.format(str(x)[2:],str(y)[:2])

Now, this an example and what I really have is a long and messy string, and so I want to put slicing inside the {}. I've studied the docs, but I can't figure out the correct syntax. My question is: is it possible to slice strings inside a replacement field?

like image 379
user1934887 Avatar asked Dec 28 '12 16:12

user1934887


People also ask

How do you slice str?

The slice() method extracts a part of a string. The slice() method returns the extracted part in a new string. The slice() method does not change the original string. The start and end parameters specifies the part of the string to extract.

Can Slicing be used for strings?

Slicing StringsYou can return a range of characters by using the slice syntax. Specify the start index and the end index, separated by a colon, to return a part of the string.

What is string slicing give example?

It's known as string slicing. The syntax that you use looks really similar to indexing. Instead of just one value being put in the square brackets, you put two with a colon ( : ) in between the two. So in this example, s is the string and m and n are the two values.

Can you slice strings in python?

The Python string data type is a sequence made up of one or more individual characters that could consist of letters, numbers, whitespace characters, or symbols. Because a string is a sequence, it can be accessed in the same ways that other sequence-based data types are, through indexing and slicing.


2 Answers

No, you can't apply slicing to strings inside a the replacement field.

You'll need to refer to the Format Specification Mini-Language; it defines what is possible. This mini language defines how you format the referenced value (the part after the : in the replacement field syntax).

like image 185
Martijn Pieters Avatar answered Oct 18 '22 14:10

Martijn Pieters


You could do something like this.

NOTE
This is a rough example and should not be considered complete and tested. But I think it shows you a way to start getting where you want to be.

import string

class SliceFormatter(string.Formatter):

    def get_value(self, key, args, kwds):
        if '|' in key:
            try:
                key, indexes = key.split('|')
                indexes = map(int, indexes.split(','))
                if key.isdigit():
                    return args[int(key)][slice(*indexes)]
                return kwds[key][slice(*indexes)]
            except KeyError:
                return kwds.get(key, 'Missing')
        return super(SliceFormatter, self).get_value(key, args, kwds)


phrase = "Hello {name|0,5}, nice to meet you.  I am {name|6,9}.  That is {0|0,4}."
fmt = SliceFormatter()
print fmt.format(phrase, "JeffJeffJeff", name="Larry Bob")

OUTPUT

Hello Larry, nice to meet you.  I am Bob.  That is Jeff.

NOTE 2
There is no support for slicing like [:5] or [6:], but I think that would be easy enough to implement as well. Also there is no error checking for slice indexes out of range, etc.

like image 20
sberry Avatar answered Oct 18 '22 16:10

sberry