Login

Trim the center of a string

Author:
grillermo
Posted:
December 5, 2012
Language:
Python
Version:
1.4
Score:
0 (after 0 ratings)

I had to build unique strings for a payment system and i wanted to make them kindof friendly so i generated them with usernames and datetimes(safe enough uniqueness in combo), some usernames are long and they break the limit of this payment system so i thought i should cut the center of the string so it stills has a part of the username and a part of the datetime, the most changing part of the datetime is of course the last part, as microseconds vary rapidly. So i wrote this little function to cut the center of a string i thought it cute so i leave it here. Pay attention to the comment so you can see what is going on.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
def trim_center_of_string(string,max_size):
    ''' 
    String: hellogoodbye 
    max_size: 8
    return hellbyes
    '''
    if len(string) >= max_size:
        # lets trim the center our long string
        length = len(string)
        excess = len(string) - max_size 
        left_imit = (length/2)-(excess/2)  # hell|os&goodbyes
        right_limit = left_imit+excess     # hellos&good|byes
        left_part = string[:left_imit]     # hell|
        right_part = string[right_limit:-1]# |byes
        string = left_part+right_part      # hellbyes
    return string

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 4 weeks ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.