Strings-OC 1.0.8__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
strings/__init__.py ADDED
@@ -0,0 +1,820 @@
1
+ # coding=utf8
2
+ """ String
3
+
4
+ Several useful helper methods for use with strings
5
+ """
6
+
7
+ __author__ = "Chris Nasr"
8
+ __copyright__ = "Ouroboros Coding Inc."
9
+ __email__ = "chris@ouroboroscoding.com"
10
+ __created__ = "2018-11-11"
11
+
12
+ # Limit exports
13
+ __all__ = [
14
+ 'bytes_human', 'cut', 'digits', 'from_file', 'join', 'normalize', 'random',
15
+ 'shorten_filename', 'strip_html', 'strtr', 'to_bool', 'to_file',
16
+ 'uuid_add_dashes', 'uuid_strip_dashes', 'version_compare'
17
+ ]
18
+
19
+ # Python imports
20
+ from html.parser import HTMLParser
21
+ from io import StringIO
22
+ import os
23
+ from secrets import randbelow
24
+ import re
25
+ from sys import _getframe, stderr
26
+ from typing import List, Literal
27
+
28
+ def bytes_human(num):
29
+ """Bytes Human
30
+
31
+ Returns the size of bytes in the closest binary prefix so that they are
32
+ clearly understood by humans
33
+
34
+ Arguments:
35
+ num (uint): The bytes to convert to human readable
36
+
37
+ Returns:
38
+ str
39
+ """
40
+
41
+ for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
42
+
43
+ if abs(num) < 1024.0:
44
+ return "%3.1f%sB" % (num, unit)
45
+
46
+ num /= 1024.0
47
+
48
+ return '%.1fYiB' % num
49
+
50
+ def cut(text: str, max_chars: int, ellipsis: str = '…'):
51
+ """Cut
52
+
53
+ Cuts text to a specific length without cutting words in half
54
+
55
+ Args:
56
+ text (str): The text to cut
57
+ max_chars (uint): The maximum number of characters to show
58
+ ellipsis (str): The text to use as an ellipsis
59
+
60
+ Returns:
61
+ str
62
+ """
63
+
64
+ # If max_chars is negative
65
+ if max_chars < 0:
66
+ raise ValueError('max_chars', 'must be an unsigned integer')
67
+
68
+ # If the string is already short enough, just return it
69
+ if len(text) <= max_chars:
70
+ return text
71
+
72
+ # Run the regex based on the length required and the ellipsis length
73
+ aM = re.search(
74
+ '^(.{0,%d})\\b' % (max_chars - len(ellipsis)),
75
+ text.strip(),
76
+ re.DOTALL
77
+ )
78
+
79
+ # If we didn't get a match
80
+ if not aM:
81
+ print(
82
+ 'strings-oc.strings.cut: can\'t match with\n%s' % text,
83
+ file = stderr
84
+ )
85
+ return text
86
+
87
+ # Return the shortened string
88
+ return aM.group(0).strip() + ellipsis
89
+
90
+ def digits(val):
91
+ """Digits
92
+
93
+ Returns only the digits in the string
94
+
95
+ Arguments:
96
+ val (str): The string to strip all non-digit characters from
97
+
98
+ Returns:
99
+ str
100
+ """
101
+
102
+ # Init list of valid characters
103
+ lRet = []
104
+
105
+ # Go through each character in the string and only keep it if it's a digit
106
+ for c in val:
107
+ if c.isdigit():
108
+ lRet.append(c)
109
+
110
+ # Return the new string
111
+ return ''.join(lRet)
112
+
113
+ def from_file(
114
+ filepath: str,
115
+ _default: str | None = None
116
+ ) -> str | None:
117
+ """From File
118
+
119
+ Returns an entire file as a single string, returns None if the file doesn't
120
+ exist
121
+
122
+ Arguments:
123
+ filepath (str): The path to the file to load
124
+
125
+ Returns:
126
+ str | None
127
+ """
128
+
129
+ try:
130
+ with open(filepath, 'r') as oF:
131
+ return oF.read()
132
+ except FileNotFoundError as e:
133
+ return _default
134
+
135
+ def join(o: dict, l: List[str], separator: str = ' ') -> str:
136
+ """Join
137
+
138
+ Creates a single string from a list of keys that may or may not exist in
139
+ the passed dict
140
+
141
+ Arguments:
142
+ o (dict): The object to pull members from
143
+ l (str[]): The list of members, in order, to join together
144
+ separator (str): Optional, char/string to join with, defaults to space
145
+
146
+ Returns:
147
+ str
148
+ """
149
+
150
+ # Init the array of found members
151
+ lFound: List[str] = []
152
+
153
+ # Go through each member passed
154
+ for s in l:
155
+
156
+ # If it exists
157
+ if s in o and isinstance(o[s], str):
158
+ lFound.append(o[s])
159
+
160
+ # Join and return
161
+ return separator.join(lFound)
162
+
163
+ def normalize(val):
164
+ """Normalize
165
+
166
+ Replaces all special alpha characters with their ascii equivalent
167
+
168
+ Arguments:
169
+ val (str): The text to normalize
170
+
171
+ Returns:
172
+ str
173
+ """
174
+ return strtr(val, {
175
+ 'Ъ': "'", 'ъ': "'", 'Ь': "'", 'ь': "'",
176
+
177
+ 'Á': 'A', 'Ă': 'A', 'Ắ': 'A', 'Ặ': 'A', 'Ằ': 'A', 'Ẳ': 'A', 'Ẵ': 'A',
178
+ 'Ǎ': 'A', 'Â': 'A', 'Ấ': 'A', 'Ậ': 'A', 'Ầ': 'A', 'Ẩ': 'A', 'Ẫ': 'A',
179
+ 'Ä': 'A', 'Ǟ': 'A', 'Ȧ': 'A', 'Ǡ': 'A', 'Ạ': 'A', 'Ȁ': 'A', 'À': 'A',
180
+ 'Ả': 'A', 'Ȃ': 'A', 'Ā': 'A', 'Ą': 'A', 'Å': 'A', 'Ǻ': 'A', 'Ḁ': 'A',
181
+ 'Ⱥ': 'A', 'Ã': 'A', 'Ɐ': 'A', 'ᴀ': 'A', 'А': 'A',
182
+ 'á': 'a', 'ă': 'a', 'ắ': 'a', 'ặ': 'a', 'ằ': 'a', 'ẳ': 'a', 'ẵ': 'a',
183
+ 'ǎ': 'a', 'â': 'a', 'ấ': 'a', 'ậ': 'a', 'ầ': 'a', 'ẩ': 'a', 'ẫ': 'a',
184
+ 'ä': 'a', 'ǟ': 'a', 'ȧ': 'a', 'ǡ': 'a', 'ạ': 'a', 'ȁ': 'a', 'à': 'a',
185
+ 'ả': 'a', 'ȃ': 'a', 'ā': 'a', 'ą': 'a', 'ᶏ': 'a', 'ẚ': 'a', 'å': 'a',
186
+ 'ǻ': 'a', 'ḁ': 'a', 'ⱥ': 'a', 'ã': 'a', 'ɐ': 'a', 'ₐ': 'a',
187
+ 'а': 'a',
188
+
189
+ 'Ꜳ': 'AA', 'Æ': 'AE', 'Ǽ': 'AE', 'Ǣ': 'AE', 'ᴁ': 'AE', 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', 'ṧ': 's', 'ş': 's', 'ŝ': 's', 'ș': 's', 'ṡ': 's', 'ṣ': 's',
330
+ 'ṩ': 's', 'ʂ': 's', 'ᵴ': 's', 'ᶊ': 's', 'ȿ': 's', 'с': 's',
331
+
332
+ 'Щ': 'SCH', 'Ш': 'SH',
333
+ 'щ': 'sch', 'ш': 'sh', 'ß': 'ss', 'st': 'st',
334
+
335
+ 'Ꞇ': 'T', 'Ť': 'T', 'Ţ': 'T', 'Ṱ': 'T', 'Ț': 'T', 'Ⱦ': 'T', 'Ṫ': 'T',
336
+ 'Ṭ': 'T', 'Ƭ': 'T', 'Ṯ': 'T', 'Ʈ': 'T', 'Ŧ': 'T', 'ᴛ': 'T', 'Т': 'T',
337
+ 'ꞇ': 't', 'ť': 't', 'ţ': 't', 'ṱ': 't', 'ț': 't', 'ȶ': 't', 'ẗ': 't',
338
+ 'ⱦ': 't', 'ṫ': 't', 'ṭ': 't', 'ƭ': 't', 'ṯ': 't', 'ᵵ': 't', 'ƫ': 't',
339
+ 'ʈ': 't', 'ŧ': 't', 'ʇ': 't', 'т': 't',
340
+
341
+ 'Ц': 'TS', 'Ꜩ': 'TZ',
342
+ 'ᵺ': 'th', 'ц': 'ts', 'ꜩ': 'tz',
343
+
344
+ 'Ú': 'U', 'Ŭ': 'U', 'Ǔ': 'U', 'Û': 'U', 'Ṷ': 'U', 'Ü': 'U', 'Ǘ': 'U',
345
+ 'Ǚ': 'U', 'Ǜ': 'U', 'Ǖ': 'U', 'Ṳ': 'U', 'Ụ': 'U', 'Ű': 'U', 'Ȕ': 'U',
346
+ 'Ù': 'U', 'Ủ': 'U', 'Ư': 'U', 'Ứ': 'U', 'Ự': 'U', 'Ừ': 'U', 'Ử': 'U',
347
+ 'Ữ': 'U', 'Ȗ': 'U', 'Ū': 'U', 'Ṻ': 'U', 'Ų': 'U', 'Ů': 'U', 'Ũ': 'U',
348
+ 'Ṹ': 'U', 'Ṵ': 'U', 'ᴜ': 'U', 'У': 'U',
349
+ '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y', 'Ỳ': 'Y', 'Ƴ': 'Y',
373
+ 'Ỷ': 'Y', 'Ỿ': 'Y', 'Ȳ': 'Y', 'Ɏ': 'Y', 'Ỹ': 'Y', 'ʏ': 'Y',
374
+ 'ʎ': 'y', 'ý': 'y', 'ŷ': 'y', 'ÿ': 'y', 'ẏ': 'y', 'ỵ': 'y', 'ỳ': 'y',
375
+ 'ƴ': 'y', 'ỷ': 'y', 'ỿ': 'y', 'ȳ': 'y', 'ẙ': 'y', 'ɏ': 'y', 'ỹ': 'y',
376
+
377
+ 'Ё': 'YO', 'Ю': 'YU', 'Я': 'Ya',
378
+ 'я': 'ya', 'ё': 'yo', 'ю': 'yu',
379
+
380
+ 'Ź': 'Z', 'Ž': 'Z', 'Ẑ': 'Z', 'Ⱬ': 'Z', 'Ż': 'Z', 'Ẓ': 'Z', 'Ȥ': 'Z',
381
+ 'Ẕ': 'Z', 'Ƶ': 'Z', 'ᴢ': 'Z', 'З': 'Z',
382
+ 'ź': 'z', 'ž': 'z', 'ẑ': 'z', 'ʑ': 'z', 'ⱬ': 'z', 'ż': 'z', 'ẓ': 'z',
383
+ 'ȥ': 'z', 'ẕ': 'z', 'ᵶ': 'z', 'ᶎ': 'z', 'ʐ': 'z', 'ƶ': 'z', 'ɀ': 'z',
384
+ 'з': 'z',
385
+
386
+ 'Ж': 'ZH',
387
+ 'ж': 'zh'
388
+ })
389
+
390
+ __random_sets = {
391
+ '0x': '0123456789abcdef',
392
+ '0': '01234567',
393
+ '10': '0123456789',
394
+ '10*': '123456789',
395
+ 'az': 'abcdefghijklmnopqrstuvwxyz',
396
+ 'az*': 'abcdefghijkmnopqrstuvwxyz',
397
+ 'AZ': 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
398
+ 'AZ*': 'ABCDEFGHJKLMNPQRSTUVWXYZ',
399
+ 'aZ': 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
400
+ 'aZ*': 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ',
401
+ '!': '!@#$%^&*-_+.?',
402
+ '!*': '!@$^*-_.'
403
+ }
404
+ """The sets available for the random function"""
405
+
406
+ def random(length = 8, characters = ['aZ'], duplicates = True):
407
+ """Random
408
+
409
+ Generates a random string. By default this function will generate an 8
410
+ character string using letters with possible repeating characters
411
+
412
+ Available sets:
413
+ 0x: 0123456789abcdef
414
+ 0: 01234567
415
+ 10: 0123456789
416
+ 10*: 123456789
417
+ az: abcdefghijklmnopqrstuvwxyz
418
+ az*: abcdefghijkmnopqrstuvwxyz
419
+ AZ: ABCDEFGHIJKLMNOPQRSTUVWXYZ
420
+ AZ*: ABCDEFGHJKLMNPQRSTUVWXYZ
421
+ aZ: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
422
+ aZ*: abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ
423
+ !: !@#$%^&*-_+.?
424
+ !*: !@$^*-_.
425
+
426
+ Sets with * remove problematic characters that can cause issues in humans or
427
+ computer systems, such as 0 (zero) or O (oh), and & which messes up
428
+ HTML/URLs
429
+
430
+ Examples:
431
+ > random(8, ['0x'])
432
+ "baadbeef"
433
+
434
+ Arguments:
435
+ length (int): Requested length of the string
436
+ characters (str|str[]): A list of names from the standard sets, or any
437
+ other string to be used as an array of characters to chose from. If
438
+ you want certain characters to have a greater chance of appearing,
439
+ use them more times, e.g. twice the 'A's, "AABC", or three times the
440
+ 'B's, "ABBBC". Make sure not to turn off duplicates for this to be
441
+ effective
442
+ duplicates (bool): Defaults to True, allowing characters to be used
443
+ more than once
444
+
445
+ Returns:
446
+ str
447
+ """
448
+
449
+ # If we got a string, store it as is
450
+ if isinstance(characters, str):
451
+ sChars = characters
452
+
453
+ # Else, if we got a list
454
+ elif isinstance(characters, list):
455
+
456
+ # Init the characters
457
+ sChars = ''
458
+
459
+ # If it's empty
460
+ if len(characters) == 0:
461
+ raise ValueError(
462
+ f'characters must contain at least one set name in {_getframe().f_code.co_name}'
463
+ )
464
+
465
+ # Go through the list of passed characters
466
+ for s in characters:
467
+
468
+ # If s is not a string
469
+ if not isinstance(s, str):
470
+ raise ValueError('%s is not a string' % s)
471
+
472
+ # Add it to the allowed characters
473
+ try:
474
+ sChars += __random_sets[s]
475
+ except KeyError:
476
+ raise ValueError('%s is not a valid set for %s' % (
477
+ s,
478
+ _getframe().f_code.co_name
479
+ ))
480
+
481
+ # Else, the value of sets is invalid
482
+ else:
483
+ raise ValueError(
484
+ f'{str(characters)} is not a valid value for sets argument of random'
485
+ )
486
+
487
+ # If we don't allow duplicates, and the length of available characters is
488
+ # less than the expected length, throw an error
489
+ if not duplicates and len(sChars) < length:
490
+ raise ValueError(
491
+ 'Can not generate random string with no duplicates from the given '
492
+ f'characters "{sChars}" in {_getframe().f_code.co_name}'
493
+ )
494
+
495
+ # Init the return variable
496
+ sText = ''
497
+
498
+ # Count the number of characters we can use
499
+ iCount = len(sChars)
500
+
501
+ # Create a [length] of random character
502
+ i = 0
503
+ while i < length:
504
+ sFound = sChars[randbelow(iCount)]
505
+ bDup = sText.find(sFound)
506
+
507
+ if duplicates or bDup == -1:
508
+ sText += sFound
509
+ i += 1
510
+
511
+ # Return the generated string
512
+ return sText
513
+
514
+ def shorten_filename(text: str, length: int) -> str:
515
+ """Shorten Filename
516
+
517
+ Makes sure the name of a file is truncated to fit the length while also
518
+ making sure not to damage or remove the extension
519
+
520
+ Arguments:
521
+ text (str): The text to truncate
522
+ length (uint): The maximum length of the string
523
+
524
+ Raises:
525
+ ValueError: If length is too small to keep the extension and at
526
+ least one character of the name
527
+
528
+ Returns:
529
+ str
530
+ """
531
+
532
+ # If the length of the string is equal or less than the length, do nothing
533
+ if len(text) <= length:
534
+ return text
535
+
536
+ # Get the last period
537
+ iPeriod = text.rfind('.')
538
+
539
+ # If there isn't one, just truncate to the requested length
540
+ if iPeriod == -1:
541
+ return text[:length]
542
+
543
+ # Store the extension and name separately
544
+ sExt = text[iPeriod:]
545
+ sName = text[:iPeriod]
546
+
547
+ # Need room for the extension (including the period) plus at least one
548
+ # name character; otherwise we would return something like ".txt"
549
+ if length < len(sExt) + 1:
550
+ raise ValueError(
551
+ 'length %d is too short to keep extension "%s" and at least '
552
+ 'one name character in %s' % (
553
+ length,
554
+ sExt,
555
+ _getframe().f_code.co_name
556
+ )
557
+ )
558
+
559
+ # Truncate the name so name + extension equals the requested length
560
+ return sName[:(length - len(sExt))] + sExt
561
+
562
+ class _StripHTML(HTMLParser):
563
+ """Strip Tags
564
+
565
+ Extends HTMLParser in order to strip the tags from a string
566
+
567
+ Extends:
568
+ HTMLParser
569
+ """
570
+
571
+ def __init__(self):
572
+ """Constructor
573
+
574
+ Creates a new instance and returns it
575
+
576
+ Returns:
577
+ _StripTags
578
+ """
579
+
580
+ # Call the parent constructor
581
+ super().__init__()
582
+
583
+ # Reset the HTMLParser instance
584
+ self.reset()
585
+
586
+ # Set flags
587
+ self.convert_charrefs = True
588
+ self.strict = False
589
+
590
+ # Create a new string file
591
+ self.text = StringIO()
592
+
593
+ def handle_data(self, d: str):
594
+ """Handle Data
595
+
596
+ Write new data to the text
597
+
598
+ Arguments:
599
+ d (str): The data to write
600
+
601
+ Returns:
602
+ None
603
+ """
604
+ self.text.write(d)
605
+
606
+ def get_data(self) -> str:
607
+ """Get Data
608
+
609
+ Return the data that's been stripped of tags
610
+
611
+ Return:
612
+ str
613
+ """
614
+ return self.text.getvalue()
615
+
616
+ def strip_html(html: str) -> str:
617
+ """Strip Tags
618
+
619
+ Takes a string with HTML and returns just the CDATA
620
+
621
+ Arguments:
622
+ html (str): The HTML to strip of tags and return
623
+
624
+ Returns:
625
+ str
626
+ """
627
+ s = _StripHTML()
628
+ s.feed(html)
629
+ return s.get_data()
630
+
631
+ def strtr(text, table):
632
+ """String Translate
633
+
634
+ Port of PHP strtr (string translate)
635
+
636
+ Arguments:
637
+ text (str): The string to translate
638
+ table (dict): The translation table
639
+
640
+ Returns:
641
+ str
642
+ """
643
+ text = str(text)
644
+ buff = []
645
+ i = 0
646
+ n = len(text)
647
+ while i < n:
648
+ for s, r in table.items():
649
+ if text[i:len(s)+i] == s:
650
+ buff.append(r)
651
+ i += len(s)
652
+ break
653
+ else:
654
+ buff.append(text[i])
655
+ i += 1
656
+
657
+ return ''.join(buff)
658
+
659
+ def to_bool(t):
660
+ """To Bool
661
+
662
+ Converts a string to a boolean value
663
+
664
+ Arguments:
665
+ t (str): The text to attempt to convert
666
+
667
+ Raises
668
+ ValueError
669
+
670
+ Returns:
671
+ bool
672
+ """
673
+
674
+ # If we didn't get a string
675
+ if not isinstance(t, str):
676
+ raise ValueError('t is not a string: %s' % str(type(t)))
677
+
678
+ # First, convert the string to lowercase
679
+ t = t.lower()
680
+
681
+ # If it's any true type value
682
+ if t in ['1', 'on', 't', 'true', 'y', 'yes', 'x']:
683
+ return True
684
+
685
+ # Else, if it's any false type value
686
+ elif t in ['0', 'f', 'false', 'n', 'no', 'off', '']:
687
+ return False
688
+
689
+ # Raise an exception
690
+ raise ValueError('"%s" is not a valid boolean representation in %s' % (
691
+ t,
692
+ _getframe().f_code.co_name
693
+ ))
694
+
695
+ def to_file(
696
+ filepath: str,
697
+ text: str,
698
+ create_path: bool = False
699
+ ) -> bool:
700
+ """To File
701
+
702
+ Stores a string to a file, overwriting the contents
703
+
704
+ Arguments:
705
+ filepath (str): The path to the file to store the string in
706
+ text (str): The text to write to the file
707
+ create_path (bool): Optional, if true, path is created if it doesn't
708
+ exist
709
+
710
+ Returns:
711
+ bool
712
+ """
713
+
714
+ try:
715
+ with open(filepath, 'w') as oF:
716
+ oF.write(text)
717
+ except FileNotFoundError:
718
+ if not create_path:
719
+ raise
720
+ sDir = os.path.dirname(filepath)
721
+ if sDir:
722
+ os.makedirs(sDir, exist_ok=True)
723
+ with open(filepath, 'w') as oF:
724
+ oF.write(text)
725
+
726
+ # return OK
727
+ return True
728
+
729
+ def uuid_add_dashes(uuid):
730
+ """UUID Add Dashes
731
+
732
+ Adds dashes back to a UUID that had them removed
733
+
734
+ Arguments:
735
+ uuid (str): The UUID to transform
736
+
737
+ Returns:
738
+ str
739
+ """
740
+
741
+ # No validation: assumes a 32-character dashless UUID and inserts
742
+ # dashes at the standard 8-4-4-4-12 boundaries
743
+ return '%s-%s-%s-%s-%s' % (
744
+ uuid[0:8],
745
+ uuid[8:12],
746
+ uuid[12:16],
747
+ uuid[16:20],
748
+ uuid[20:32]
749
+ )
750
+
751
+ def uuid_strip_dashes(uuid):
752
+ """UUID Strip Dashes
753
+
754
+ Removes the dashes from a UUID
755
+
756
+ Arguments:
757
+ uuid (str): The UUID to transform
758
+
759
+ Returns:
760
+ str
761
+ """
762
+
763
+ # No validation: assumes a canonical 8-4-4-4-12 dashed UUID and
764
+ # removes characters at the dash indexes; invalid input will produce
765
+ # a corrupted result
766
+ return '%s%s%s%s%s' % (
767
+ uuid[0:8],
768
+ uuid[9:13],
769
+ uuid[14:18],
770
+ uuid[19:23],
771
+ uuid[24:36]
772
+ )
773
+
774
+ def version_compare(
775
+ a: str,
776
+ b: str
777
+ ) -> Literal[-1] | Literal[0] | Literal[1]:
778
+ """Version Compare
779
+
780
+ Compares two version strings and returns whether the first one is less
781
+ than (-1), equal (0), or greater than (1)
782
+
783
+ Arguments:
784
+ a (str): The first version
785
+ b (str): The second version
786
+
787
+ Returns:
788
+ -1 | 0 | 1
789
+ """
790
+
791
+ # First, convert both strings to int lists
792
+ lA = [int(s) for s in a.split('.')]
793
+ lB = [int(s) for s in b.split('.')]
794
+
795
+ # Get the lengths of each
796
+ iA = len(lA)
797
+ iB = len(lB)
798
+ iLength = iA
799
+
800
+ # Make sure the lists are equal in length
801
+ if iA < iB:
802
+ for i in range(iB - iA):
803
+ lA.append(0)
804
+ iLength = iB
805
+ elif iA > iB:
806
+ for i in range(iA - iB):
807
+ lB.append(0)
808
+
809
+ # Go through the range
810
+ for i in range(iLength):
811
+
812
+ # If the values are the same
813
+ if lA[i] == lB[i]:
814
+ continue
815
+
816
+ # Return if A is less than or greater than
817
+ return lA[i] < lB[i] and -1 or 1
818
+
819
+ # No difference
820
+ return 0
strings/__main__.py ADDED
@@ -0,0 +1 @@
1
+ print('I compile, but I don\'t necessarily run')
@@ -0,0 +1,306 @@
1
+ Metadata-Version: 2.5
2
+ Name: strings_oc
3
+ Version: 1.0.8
4
+ Summary: Generic functions for dealing with and generating strings
5
+ Project-URL: Documentation, https://ouroboroscoding.com/strings/
6
+ Project-URL: Source, https://github.com/ouroboroscoding/strings-python
7
+ Project-URL: Tracker, https://github.com/ouroboroscoding/strings-python/issues
8
+ Author-email: "Chris Nasr - Ouroboros Coding Inc." <chris@ouroboroscoding.com>
9
+ Maintainer-email: "Chris Nasr - Ouroboros Coding Inc." <chris@ouroboroscoding.com>
10
+ License-File: LICENSE
11
+ Keywords: string generation,string manipulation,strings
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+
15
+ # Strings by Ouroboros Coding
16
+ [![pypi version](https://img.shields.io/pypi/v/strings_oc.svg)](https://pypi.org/project/strings_oc) ![MIT License](https://img.shields.io/pypi/l/strings_oc.svg)
17
+
18
+ Generic functions for dealing with and generating strings
19
+
20
+ Please see [LICENSE](https://github.com/ouroboroscoding/strings-python/blob/main/LICENSE)
21
+ for further information.
22
+
23
+ See [Releases](https://github.com/ouroboroscoding/strings-python/blob/main/releases.md)
24
+ for changes from release to release.
25
+
26
+ ## Requires
27
+ strings_oc requires python 3.10 or higher
28
+
29
+ ## Installation
30
+ ```bash
31
+ pip install strings_oc
32
+ ```
33
+
34
+ ## Functions
35
+
36
+ ### bytes_human
37
+ Returns a human readable string using the number passed as a representation of
38
+ bytes
39
+ ```python
40
+ >>> from strings import bytes_human
41
+ >>> bytes_human(1024)
42
+ '1.0KiB'
43
+ >>> bytes_human(1024*1024)
44
+ '1.0MiB'
45
+ >>> bytes_human(1024*1024*1024+1000000000)
46
+ '1.9GiB'
47
+ ```
48
+
49
+ ### cut
50
+ Shortens a string so that it ends on a full word instead of halfway between
51
+ words.
52
+ ```python
53
+ >>> from strings import cut
54
+ >>> cut('12345 7890', 8)
55
+ '12345…'
56
+ >>> cut('12345 7890', 8, '...')
57
+ '12345...'
58
+ >>> cut('Hello, my name is Frank', 16)
59
+ 'Hello, my name…'
60
+ ```
61
+
62
+ ### digits
63
+ Returns only the digits, i.e. the numeric characters, in the given string as a
64
+ new string. Be careful, as this does not return numbers, but number characters,
65
+ and will strip out valid float/decimal characters
66
+ ```python
67
+ >>> from strings import digits
68
+ >>> digits('1234abcd')
69
+ '1234'
70
+ >>> digits('a1b2c3d4')
71
+ '1234'
72
+ >>> digits('3.1415')
73
+ '31415'
74
+ >>> digits('1e+7')
75
+ '17'
76
+ ```
77
+
78
+ ### from_file
79
+ Returns the entire file as a string
80
+
81
+ ```python
82
+ >>> from strings import from_file
83
+ >>> from_file('version.dat')
84
+ '1.0.1\n'
85
+ ```
86
+
87
+ Assuming `version.dat` contained the following
88
+
89
+ ```
90
+ 1.0.1
91
+
92
+ ```
93
+
94
+ If the file doesn't exist, `from_file` returns `None`. This can be changed by
95
+ passing a second argument to be the default value.
96
+
97
+ ```python
98
+ >>> from strings import from_file
99
+ >>> from_file('doesnotexist', '1.0.0')
100
+ '1.0.0'
101
+ ```
102
+
103
+ ### join
104
+ `join` creates a single string from a list of keys that may or may not exist in
105
+ the passed dict.
106
+ ```python
107
+ >>> from strings import join
108
+ >>> d = { 'title': 'Mr.', 'first': 'Homer', 'last': 'Simpson' }
109
+ >>> join(d, ['title', 'first', 'last', 'post'])
110
+ 'Mr. Homer Simpson'
111
+ >>> d = { 'title': 'Dr.', 'first': 'Julius', 'last': 'Hibbert', 'post': 'MD' }
112
+ 'Dr. Julius Hibbert MD'
113
+ ```
114
+
115
+ ### normalize
116
+ Returns, as well as possible, a normalized string converted from another string
117
+ containing characters with special accents. It does this by finding special
118
+ characters and converting them into their simpler, single character, versions.
119
+ This is useful for things like automaticlaly generating urls, or for generating
120
+ from unicode into ascii.
121
+ ```python
122
+ >>> from strings import normalize
123
+ >>> normalize('Ȟěƚľỡ, Ẉợɽḷᶁ!')
124
+ 'Hello, World!'
125
+ >>> normalize('ffiDzǼij')
126
+ 'ffiDAEij'
127
+ ```
128
+
129
+ ### random
130
+ Returns a random string based on set parameters.
131
+ ```python
132
+ >>> from strings import random
133
+ >>> random()
134
+ 'NQFsxVTi'
135
+ >>> random()
136
+ 'KFCMjKQg'
137
+ >>> random()
138
+ 'HJEvCjlA'
139
+ ```
140
+ `random` can takes 3 optional parameters.
141
+ #### length
142
+ `length` represents the number of random characters you wish to return.
143
+ ```python
144
+ >>> random(length = 10)
145
+ 'PvIwnubCyN'
146
+ >>> random(length = 4)
147
+ 'bGXE'
148
+ >>> random(16)
149
+ 'WMLdawtSCEFeNtsg'
150
+ ```
151
+ #### characters
152
+ `characters` represents the set of chars that are allowed in the string. There
153
+ is no limit on this list, and no necessity the values be different. This allows
154
+ for modifying the randomness if there are characters you want to make "more
155
+ random"
156
+ ```python
157
+ >>> random(8, 'AAAAa')
158
+ 'AAAAAAAA'
159
+ >>> random(length = 8, characters = 'AAAaa')
160
+ 'aAAAAAaA'
161
+ >>> random(characters = 'AAaaa', length = 8)
162
+ 'aaaaAAaA'
163
+ ```
164
+ `characters` can be set using special built in sets, and can be accessed by
165
+ passing a list instead of a string
166
+ ```python
167
+ >>> random(16, ['aZ'])
168
+ 'KwDNSoFPlVVTxwhj'
169
+ >>> random(characters = ['az*', '10'])
170
+ 'a003jsut'
171
+ >>> random(characters = ['0x'], length = 32)
172
+ '9ce511ab223cef1d65c400ce2e836759'
173
+ ```
174
+
175
+ | name | characters |
176
+ | --- | --- |
177
+ | 0x | 0123456789abcdef |
178
+ | 0 | 01234567 |
179
+ | 10 | 0123456789 |
180
+ | 10* | 123456789 |
181
+ | az | abcdefghijklmnopqrstuvwxyz |
182
+ | az* | abcdefghijkmnopqrstuvwxyz |
183
+ | AZ | ABCDEFGHIJKLMNOPQRSTUVWXYZ |
184
+ | AZ* | ABCDEFGHJKLMNPQRSTUVWXYZ |
185
+ | aZ | abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ |
186
+ | aZ* | abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ |
187
+ | ! | !@#$%^&*-_+.? |
188
+ | !* | !@$^*-_. |
189
+
190
+ \* sets denote removal of characters that might confuse, either systems or
191
+ humans. &, #, etc for the former, and I, l, O, etc for the latter.
192
+ #### duplicates
193
+ By default `random` allows duplicate characters in a string, and doesn't see any
194
+ issue with that. But it's possible you have an issue with it, and want a string
195
+ made up completely of non-repeating characters. If so, set `duplicates` to
196
+ `False`.
197
+ ```python
198
+ >>> random(16, ['az'], False)
199
+ 'ifaunxgtzbywkmpr'
200
+ >>> random(26, ['az'], False)
201
+ 'rmqghwsayntkpizfbeldvcxoju'
202
+ >>> random(27, ['az'], False)
203
+ ValueError: Can not generate random string with no duplicates from the given characters "abcdefghijklmnopqrstuvwxyz" in random
204
+ ```
205
+
206
+ ### shorten_filename
207
+ `shorten_filename` allows for truncating filenames without losing or damaging
208
+ the extension of the file. Useful for when you need to add a filename for an
209
+ uploaded file to a database and you are limited by the length of the field.
210
+ ```python
211
+ >>> from strings import shorten_filename
212
+ >>> shorten_filename('hello_there_my_friend.txt', 16)
213
+ 'hello_there_.txt'
214
+ ```
215
+ As you can see, the name part of the file is shortened, but the .txt stays
216
+ intact, avoiding potential problems with mime lookup. If the requested length
217
+ is too short to keep the extension and at least one character of the name, a
218
+ `ValueError` is raised.
219
+
220
+ ### strip_html
221
+ `strip_html` takes an HTML string and removes all the tags/elements while
222
+ retaining the cdata. Useful for content that needs to be displayed without
223
+ formatting.
224
+ ```python
225
+ >>> from strings import strip_html
226
+ >>> strip_html('<p>This is a test</p>')
227
+ 'This is a test'
228
+ >>> strip_html('<p>Wanna see some <b>BOLD</b> text?</p>')
229
+ 'Wanna see some BOLD text?'
230
+ ```
231
+
232
+ ### strtr
233
+ `strtr` is a partial copy of the [PHP functon](https://www.php.net/manual/en/function.strtr.php) of the same name. This version does not support the singular use of one $from, and one $to, but the same can be achieved by using a dict with a single key and value. The primary purpose of this function is to be the actual workhorse of the `normalize` function, but there's no reason other people can't make use of it.
234
+ ```python
235
+ >>> from strings import strtr
236
+ >>> strtr('Hello, World!', {'World': 'Chris'})
237
+ 'Hello, Chris!'
238
+ ```
239
+
240
+ ### to_bool
241
+ `to_bool` is useful for turning any string into a valid boolean. But will raise
242
+ an exception if the value does not represent a bool as it sees it. First, it
243
+ converts the string to lowercase, then it checks it against the following:
244
+
245
+ Valid `True` values contain '1', 'on', 't', 'true', 'y', 'yes', 'x'
246
+
247
+ Valid `False` values contain '0', 'f', 'false', 'n', 'no', 'off', ''
248
+ ```python
249
+ >>> from strings import to_bool
250
+ >>> to_bool('true')
251
+ True
252
+ >>> to_bool('F')
253
+ False
254
+ >>> to_bool('2')
255
+ ValueError: "2" is not a valid boolean representation in to_bool
256
+ ```
257
+
258
+ ### to_file
259
+ Stores a string in a file, overwriting the existing contents, or creating the
260
+ file if it didn't exist. Pass `create_path = True` to create missing parent
261
+ directories; with the default `create_path = False`, a missing directory raises
262
+ `FileNotFoundError`.
263
+ ```python
264
+ >>> from strings import to_file
265
+ >>> to_file('version.dat', '1.1.0')
266
+ True
267
+ >>> to_file('does/not/exist/version.dat', '1.1.0', create_path = True)
268
+ True
269
+ ```
270
+ The `version.dat` file will now contain the following
271
+ ```
272
+ 1.1.0
273
+ ```
274
+
275
+ ### uuid_add_dashes
276
+ Used to add dashes "-" to a string representation of a UUID that has none. Does
277
+ not validate the input; it assumes a 32-character dashless UUID and inserts
278
+ dashes at the standard 8-4-4-4-12 boundaries.
279
+ ```python
280
+ >>> from strings import uuid_add_dashes
281
+ >>> uuid_add_dashes('b22eb45ac98311eca05a80fa5b0d7c77')
282
+ 'b22eb45a-c983-11ec-a05a-80fa5b0d7c77'
283
+ ```
284
+
285
+ ### uuid_strip_dashes
286
+ Used to strip dashes "-" from a string representation of a UUID that has them.
287
+ Does not validate the input; it assumes a canonical dashed UUID. Invalid input
288
+ will produce a corrupted result.
289
+ ```python
290
+ >>> from strings import uuid_strip_dashes
291
+ >>> uuid_strip_dashes('b22eb45a-c983-11ec-a05a-80fa5b0d7c77')
292
+ 'b22eb45ac98311eca05a80fa5b0d7c77'
293
+ ```
294
+
295
+ ### version_compare
296
+ Compares to version strings and returns if the first is less than (-1), equal to
297
+ (0) or greater than (1) the second.
298
+ ```python
299
+ >>> from strings import version_compare
300
+ >>> version_compare('1.0.1', '1.0')
301
+ 1
302
+ >>> version_compare('1.0.1', '1.0.1')
303
+ 0
304
+ >>> version_compare('1.0.1', '1.1')
305
+ -1
306
+ ```
@@ -0,0 +1,6 @@
1
+ strings/__init__.py,sha256=P02eBt21OtEf9dy_e5zrQhe_NHyQsi6LnXyLJ82gr0I,23306
2
+ strings/__main__.py,sha256=qxPLqwdqExh6ARRJNMD8bgD4VMoM96_s82rVexMfyJs,48
3
+ strings_oc-1.0.8.dist-info/METADATA,sha256=XMohCYngAFZKOyPmsv6O6C_-bmxgpXgZ02WNqYPrK3M,9381
4
+ strings_oc-1.0.8.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
5
+ strings_oc-1.0.8.dist-info/licenses/LICENSE,sha256=5RMNwznBsSdPwWKL2usG73FA0_6m1HSRW0DHY3N0gzI,1077
6
+ strings_oc-1.0.8.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ouroboros Coding Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.