File: Seq.py

package info (click to toggle)
python-biopython 1.73%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 57,852 kB
  • sloc: python: 169,977; xml: 97,539; ansic: 15,653; sql: 1,208; makefile: 159; sh: 63
file content (2819 lines) | stat: -rw-r--r-- 108,503 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
# Copyright 2000 Andrew Dalke.
# Copyright 2000-2002 Brad Chapman.
# Copyright 2004-2005, 2010 by M de Hoon.
# Copyright 2007-2018 by Peter Cock.
# All rights reserved.
#
# This file is part of the Biopython distribution and governed by your
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
# Please see the LICENSE file that should have been included as part of this
# package.
"""Provide objects to represent biological sequences with alphabets.

See also the Seq_ wiki and the chapter in our tutorial:
 - `HTML Tutorial`_
 - `PDF Tutorial`_

.. _Seq: http://biopython.org/wiki/Seq
.. _`HTML Tutorial`: http://biopython.org/DIST/docs/tutorial/Tutorial.html
.. _`PDF Tutorial`: http://biopython.org/DIST/docs/tutorial/Tutorial.pdf

"""
from __future__ import print_function

import string  # for maketrans only
import array
import sys
import warnings

from Bio._py3k import range
from Bio._py3k import basestring

from Bio import BiopythonWarning
from Bio import Alphabet
from Bio.Alphabet import IUPAC
from Bio.Data.IUPACData import (ambiguous_dna_complement,
                                ambiguous_rna_complement)
from Bio.Data.IUPACData import ambiguous_dna_letters as _ambiguous_dna_letters
from Bio.Data.IUPACData import ambiguous_rna_letters as _ambiguous_rna_letters
from Bio.Data import CodonTable


def _maketrans(complement_mapping):
    """Make a python string translation table (PRIVATE).

    Arguments:
     - complement_mapping - a dictionary such as ambiguous_dna_complement
       and ambiguous_rna_complement from Data.IUPACData.

    Returns a translation table (a string of length 256) for use with the
    python string's translate method to use in a (reverse) complement.

    Compatible with lower case and upper case sequences.

    For internal use only.
    """
    before = ''.join(complement_mapping.keys())
    after = ''.join(complement_mapping.values())
    before += before.lower()
    after += after.lower()
    if sys.version_info[0] == 3:
        return str.maketrans(before, after)
    else:
        return string.maketrans(before, after)


_dna_complement_table = _maketrans(ambiguous_dna_complement)
_rna_complement_table = _maketrans(ambiguous_rna_complement)


class Seq(object):
    """Read-only sequence object (essentially a string with an alphabet).

    Like normal python strings, our basic sequence object is immutable.
    This prevents you from doing my_seq[5] = "A" for example, but does allow
    Seq objects to be used as dictionary keys.

    The Seq object provides a number of string like methods (such as count,
    find, split and strip), which are alphabet aware where appropriate.

    In addition to the string like sequence, the Seq object has an alphabet
    property. This is an instance of an Alphabet class from Bio.Alphabet,
    for example generic DNA, or IUPAC DNA. This describes the type of molecule
    (e.g. RNA, DNA, protein) and may also indicate the expected symbols
    (letters).

    The Seq object also provides some biological methods, such as complement,
    reverse_complement, transcribe, back_transcribe and translate (which are
    not applicable to sequences with a protein alphabet).
    """

    def __init__(self, data, alphabet=Alphabet.generic_alphabet):
        """Create a Seq object.

        Arguments:
         - seq - Sequence, required (string)
         - alphabet - Optional argument, an Alphabet object from
           Bio.Alphabet

        You will typically use Bio.SeqIO to read in sequences from files as
        SeqRecord objects, whose sequence will be exposed as a Seq object via
        the seq property.

        However, will often want to create your own Seq objects directly:

        >>> from Bio.Seq import Seq
        >>> from Bio.Alphabet import IUPAC
        >>> my_seq = Seq("MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF",
        ...              IUPAC.protein)
        >>> my_seq
        Seq('MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF', IUPACProtein())
        >>> print(my_seq)
        MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF
        >>> my_seq.alphabet
        IUPACProtein()
        """
        # Enforce string storage
        if not isinstance(data, basestring):
            raise TypeError("The sequence data given to a Seq object should "
                            "be a string (not another Seq object etc)")
        self._data = data
        self.alphabet = alphabet  # Seq API requirement

    def __repr__(self):
        """Return (truncated) representation of the sequence for debugging."""
        if self.alphabet is Alphabet.generic_alphabet:
            # Default used, we can omit it and simplify the representation
            a = ""
        else:
            a = ", %r" % self.alphabet
        if len(self) > 60:
            # Shows the last three letters as it is often useful to see if
            # there is a stop codon at the end of a sequence.
            # Note total length is 54+3+3=60
            return "{0}('{1}...{2}'{3!s})".format(self.__class__.__name__,
                                                  str(self)[:54],
                                                  str(self)[-3:],
                                                  a)
        else:
            return '{0}({1!r}{2!s})'.format(self.__class__.__name__,
                                            self._data,
                                            a)

    def __str__(self):
        """Return the full sequence as a python string, use str(my_seq).

        Note that Biopython 1.44 and earlier would give a truncated
        version of repr(my_seq) for str(my_seq).  If you are writing code
        which need to be backwards compatible with old Biopython, you
        should continue to use my_seq.tostring() rather than str(my_seq).
        """
        return self._data

    def __hash__(self):
        """Hash for comparison.

        See the __cmp__ documentation - this has changed from past
        versions of Biopython!
        """
        # TODO - remove this warning in a future release
        warnings.warn("Biopython Seq objects now use string comparison. "
                      "Older versions of Biopython used object comparison. "
                      "During this transition, please use hash(id(my_seq)) "
                      "or my_dict[id(my_seq)] if you want the old behaviour, "
                      "or use hash(str(my_seq)) or my_dict[str(my_seq)] for "
                      "the new string hashing behaviour.", BiopythonWarning)
        return hash(str(self))

    def __eq__(self, other):
        """Compare the sequence to another sequence or a string (README).

        Historically comparing Seq objects has done Python object comparison.
        After considerable discussion (keeping in mind constraints of the
        Python language, hashes and dictionary support), Biopython now uses
        simple string comparison (with a warning about the change).

        Note that incompatible alphabets (e.g. DNA to RNA) will trigger a
        warning.

        During this transition period, please just do explicit comparisons:

        >>> from Bio.Seq import Seq
        >>> from Bio.Alphabet import generic_dna
        >>> seq1 = Seq("ACGT")
        >>> seq2 = Seq("ACGT")
        >>> id(seq1) == id(seq2)
        False
        >>> str(seq1) == str(seq2)
        True

        The new behaviour is to use string-like equality:

        >>> from Bio.Seq import Seq
        >>> from Bio.Alphabet import generic_dna
        >>> seq1 == seq2
        True
        >>> seq1 == "ACGT"
        True
        >>> seq1 == Seq("ACGT", generic_dna)
        True

        """
        if hasattr(other, "alphabet"):
            # other could be a Seq or a MutableSeq
            if not Alphabet._check_type_compatible([self.alphabet,
                                                    other.alphabet]):
                warnings.warn("Incompatible alphabets {0!r} and {1!r}".format(
                              self.alphabet, other.alphabet),
                              BiopythonWarning)
        return str(self) == str(other)

    def __ne__(self, other):
        """Implement the not-equal operand."""
        # Require this method for Python 2 but not needed on Python 3
        return not self == other

    def __lt__(self, other):
        """Implement the less-than operand."""
        if hasattr(other, "alphabet"):
            if not Alphabet._check_type_compatible([self.alphabet,
                                                    other.alphabet]):
                warnings.warn("Incompatible alphabets {0!r} and {1!r}".format(
                              self.alphabet, other.alphabet),
                              BiopythonWarning)
        if isinstance(other, (str, Seq, MutableSeq, UnknownSeq)):
            return str(self) < str(other)
        raise TypeError("'<' not supported between instances of '{}' and '{}'"
                        .format(type(self).__name__, type(other).__name__))

    def __le__(self, other):
        """Implement the less-than or equal operand."""
        if hasattr(other, "alphabet"):
            if not Alphabet._check_type_compatible([self.alphabet,
                                                    other.alphabet]):
                warnings.warn("Incompatible alphabets {0!r} and {1!r}".format(
                              self.alphabet, other.alphabet),
                              BiopythonWarning)
        if isinstance(other, (str, Seq, MutableSeq, UnknownSeq)):
            return str(self) <= str(other)
        raise TypeError("'<=' not supported between instances of '{}' and '{}'"
                        .format(type(self).__name__, type(other).__name__))

    def __gt__(self, other):
        """Implement the greater-than operand."""
        if hasattr(other, "alphabet"):
            if not Alphabet._check_type_compatible([self.alphabet,
                                                    other.alphabet]):
                warnings.warn("Incompatible alphabets {0!r} and {1!r}".format(
                              self.alphabet, other.alphabet),
                              BiopythonWarning)
        if isinstance(other, (str, Seq, MutableSeq, UnknownSeq)):
            return str(self) > str(other)
        raise TypeError("'>' not supported between instances of '{}' and '{}'"
                        .format(type(self).__name__, type(other).__name__))

    def __ge__(self, other):
        """Implement the greater-than or equal operand."""
        if hasattr(other, "alphabet"):
            if not Alphabet._check_type_compatible([self.alphabet,
                                                    other.alphabet]):
                warnings.warn("Incompatible alphabets {0!r} and {1!r}".format(
                              self.alphabet, other.alphabet),
                              BiopythonWarning)
        if isinstance(other, (str, Seq, MutableSeq, UnknownSeq)):
            return str(self) >= str(other)
        raise TypeError("'>=' not supported between instances of '{}' and '{}'"
                        .format(type(self).__name__, type(other).__name__))

    def __len__(self):
        """Return the length of the sequence, use len(my_seq)."""
        return len(self._data)  # Seq API requirement

    def __getitem__(self, index):  # Seq API requirement
        """Return a subsequence of single letter, use my_seq[index].

        >>> my_seq = Seq('ACTCGACGTCG')
        >>> my_seq[5]
        'A'
        """
        # Note since Python 2.0, __getslice__ is deprecated
        # and __getitem__ is used instead.
        # See http://docs.python.org/ref/sequence-methods.html
        if isinstance(index, int):
            # Return a single letter as a string
            return self._data[index]
        else:
            # Return the (sub)sequence as another Seq object
            return Seq(self._data[index], self.alphabet)

    def __add__(self, other):
        """Add another sequence or string to this sequence.

        If adding a string to a Seq, the alphabet is preserved:

        >>> from Bio.Seq import Seq
        >>> from Bio.Alphabet import generic_protein
        >>> Seq("MELKI", generic_protein) + "LV"
        Seq('MELKILV', ProteinAlphabet())

        When adding two Seq (like) objects, the alphabets are important.
        Consider this example:

        >>> from Bio.Seq import Seq
        >>> from Bio.Alphabet.IUPAC import unambiguous_dna, ambiguous_dna
        >>> unamb_dna_seq = Seq("ACGT", unambiguous_dna)
        >>> ambig_dna_seq = Seq("ACRGT", ambiguous_dna)
        >>> unamb_dna_seq
        Seq('ACGT', IUPACUnambiguousDNA())
        >>> ambig_dna_seq
        Seq('ACRGT', IUPACAmbiguousDNA())

        If we add the ambiguous and unambiguous IUPAC DNA alphabets, we get
        the more general ambiguous IUPAC DNA alphabet:

        >>> unamb_dna_seq + ambig_dna_seq
        Seq('ACGTACRGT', IUPACAmbiguousDNA())

        However, if the default generic alphabet is included, the result is
        a generic alphabet:

        >>> Seq("") + ambig_dna_seq
        Seq('ACRGT')

        You can't add RNA and DNA sequences:

        >>> from Bio.Alphabet import generic_dna, generic_rna
        >>> Seq("ACGT", generic_dna) + Seq("ACGU", generic_rna)
        Traceback (most recent call last):
           ...
        TypeError: Incompatible alphabets DNAAlphabet() and RNAAlphabet()

        You can't add nucleotide and protein sequences:

        >>> from Bio.Alphabet import generic_dna, generic_protein
        >>> Seq("ACGT", generic_dna) + Seq("MELKI", generic_protein)
        Traceback (most recent call last):
           ...
        TypeError: Incompatible alphabets DNAAlphabet() and ProteinAlphabet()
        """
        if hasattr(other, "alphabet"):
            # other should be a Seq or a MutableSeq
            if not Alphabet._check_type_compatible([self.alphabet,
                                                    other.alphabet]):
                raise TypeError(
                    "Incompatible alphabets {0!r} and {1!r}".format(
                        self.alphabet, other.alphabet))
            # They should be the same sequence type (or one of them is generic)
            a = Alphabet._consensus_alphabet([self.alphabet, other.alphabet])
            return self.__class__(str(self) + str(other), a)
        elif isinstance(other, basestring):
            # other is a plain string - use the current alphabet
            return self.__class__(str(self) + other, self.alphabet)
        from Bio.SeqRecord import SeqRecord  # Lazy to avoid circular imports
        if isinstance(other, SeqRecord):
            # Get the SeqRecord's __radd__ to handle this
            return NotImplemented
        else:
            raise TypeError

    def __radd__(self, other):
        """Add a sequence on the left.

        If adding a string to a Seq, the alphabet is preserved:

        >>> from Bio.Seq import Seq
        >>> from Bio.Alphabet import generic_protein
        >>> "LV" + Seq("MELKI", generic_protein)
        Seq('LVMELKI', ProteinAlphabet())

        Adding two Seq (like) objects is handled via the __add__ method.
        """
        if hasattr(other, "alphabet"):
            # other should be a Seq or a MutableSeq
            if not Alphabet._check_type_compatible([self.alphabet,
                                                    other.alphabet]):
                raise TypeError(
                    "Incompatible alphabets {0!r} and {1!r}".format(
                        self.alphabet, other.alphabet))
            # They should be the same sequence type (or one of them is generic)
            a = Alphabet._consensus_alphabet([self.alphabet, other.alphabet])
            return self.__class__(str(other) + str(self), a)
        elif isinstance(other, basestring):
            # other is a plain string - use the current alphabet
            return self.__class__(other + str(self), self.alphabet)
        else:
            raise TypeError

    def __mul__(self, other):
        """Multiply Seq by integer.

        >>> from Bio.Seq import Seq
        >>> from Bio.Alphabet import generic_dna
        >>> Seq('ATG') * 2
        Seq('ATGATG')
        >>> Seq('ATG', generic_dna) * 2
        Seq('ATGATG', DNAAlphabet())
        """
        if not isinstance(other, int):
            raise TypeError("can't multiply {} by non-int type".format(self.__class__.__name__))
        return self.__class__(str(self) * other, self.alphabet)

    def __rmul__(self, other):
        """Multiply integer by Seq.

        >>> from Bio.Seq import Seq
        >>> from Bio.Alphabet import generic_dna
        >>> 2 * Seq('ATG')
        Seq('ATGATG')
        >>> 2 * Seq('ATG', generic_dna)
        Seq('ATGATG', DNAAlphabet())
        """
        if not isinstance(other, int):
            raise TypeError("can't multiply {} by non-int type".format(self.__class__.__name__))
        return self.__class__(str(self) * other, self.alphabet)

    def __imul__(self, other):
        """Multiply Seq in-place.

        Note although Seq is immutable, the in-place method is
        included to match the behaviour for regular Python strings.

        >>> from Bio.Seq import Seq
        >>> from Bio.Alphabet import generic_dna
        >>> seq = Seq('ATG', generic_dna)
        >>> seq *= 2
        >>> seq
        Seq('ATGATG', DNAAlphabet())
        """
        if not isinstance(other, int):
            raise TypeError("can't multiply {} by non-int type".format(self.__class__.__name__))
        return self.__class__(str(self) * other, self.alphabet)

    def tomutable(self):  # Needed?  Or use a function?
        """Return the full sequence as a MutableSeq object.

        >>> from Bio.Seq import Seq
        >>> from Bio.Alphabet import IUPAC
        >>> my_seq = Seq("MKQHKAMIVALIVICITAVVAAL",
        ...              IUPAC.protein)
        >>> my_seq
        Seq('MKQHKAMIVALIVICITAVVAAL', IUPACProtein())
        >>> my_seq.tomutable()
        MutableSeq('MKQHKAMIVALIVICITAVVAAL', IUPACProtein())

        Note that the alphabet is preserved.
        """
        return MutableSeq(str(self), self.alphabet)

    def _get_seq_str_and_check_alphabet(self, other_sequence):
        """Convert string/Seq/MutableSeq to string, checking alphabet (PRIVATE).

        For a string argument, returns the string.

        For a Seq or MutableSeq, it checks the alphabet is compatible
        (raising an exception if it isn't), and then returns a string.
        """
        try:
            other_alpha = other_sequence.alphabet
        except AttributeError:
            # Assume other_sequence is a string
            return other_sequence

        # Other should be a Seq or a MutableSeq
        if not Alphabet._check_type_compatible([self.alphabet, other_alpha]):
            raise TypeError("Incompatible alphabets {0!r} and {1!r}".format(
                            self.alphabet, other_alpha))
        # Return as a string
        return str(other_sequence)

    def count(self, sub, start=0, end=sys.maxsize):
        """Return a non-overlapping count, like that of a python string.

        This behaves like the python string method of the same name,
        which does a non-overlapping count!

        For an overlapping search use the newer count_overlap() method.

        Returns an integer, the number of occurrences of substring
        argument sub in the (sub)sequence given by [start:end].
        Optional arguments start and end are interpreted as in slice
        notation.

        Arguments:
         - sub - a string or another Seq object to look for
         - start - optional integer, slice start
         - end - optional integer, slice end

        e.g.

        >>> from Bio.Seq import Seq
        >>> my_seq = Seq("AAAATGA")
        >>> print(my_seq.count("A"))
        5
        >>> print(my_seq.count("ATG"))
        1
        >>> print(my_seq.count(Seq("AT")))
        1
        >>> print(my_seq.count("AT", 2, -1))
        1

        HOWEVER, please note because python strings and Seq objects (and
        MutableSeq objects) do a non-overlapping search, this may not give
        the answer you expect:

        >>> "AAAA".count("AA")
        2
        >>> print(Seq("AAAA").count("AA"))
        2

        An overlapping search, as implemented in .count_overlap(),
        would give the answer as three!
        """
        # If it has one, check the alphabet:
        sub_str = self._get_seq_str_and_check_alphabet(sub)
        return str(self).count(sub_str, start, end)

    def count_overlap(self, sub, start=0, end=sys.maxsize):
        """Return an overlapping count.

        For a non-overlapping search use the count() method.

        Returns an integer, the number of occurrences of substring
        argument sub in the (sub)sequence given by [start:end].
        Optional arguments start and end are interpreted as in slice
        notation.

        Arguments:
         - sub - a string or another Seq object to look for
         - start - optional integer, slice start
         - end - optional integer, slice end

        e.g.

        >>> from Bio.Seq import Seq
        >>> print(Seq("AAAA").count_overlap("AA"))
        3
        >>> print(Seq("ATATATATA").count_overlap("ATA"))
        4
        >>> print(Seq("ATATATATA").count_overlap("ATA", 3, -1))
        1

        Where substrings do not overlap, should behave the same as
        the count() method:

        >>> from Bio.Seq import Seq
        >>> my_seq = Seq("AAAATGA")
        >>> print(my_seq.count_overlap("A"))
        5
        >>> my_seq.count_overlap("A") == my_seq.count("A")
        True
        >>> print(my_seq.count_overlap("ATG"))
        1
        >>> my_seq.count_overlap("ATG") == my_seq.count("ATG")
        True
        >>> print(my_seq.count_overlap(Seq("AT")))
        1
        >>> my_seq.count_overlap(Seq("AT")) == my_seq.count(Seq("AT"))
        True
        >>> print(my_seq.count_overlap("AT", 2, -1))
        1
        >>> my_seq.count_overlap("AT", 2, -1) == my_seq.count("AT", 2, -1)
        True

        HOWEVER, do not use this method for such cases because the
        count() method is much for efficient.
        """
        sub_str = self._get_seq_str_and_check_alphabet(sub)
        self_str = str(self)
        overlap_count = 0
        while True:
            start = self_str.find(sub_str, start, end) + 1
            if start != 0:
                overlap_count += 1
            else:
                return overlap_count

    def __contains__(self, char):
        """Implement the 'in' keyword, like a python string.

        e.g.

        >>> from Bio.Seq import Seq
        >>> from Bio.Alphabet import generic_dna, generic_rna, generic_protein
        >>> my_dna = Seq("ATATGAAATTTGAAAA", generic_dna)
        >>> "AAA" in my_dna
        True
        >>> Seq("AAA") in my_dna
        True
        >>> Seq("AAA", generic_dna) in my_dna
        True

        Like other Seq methods, this will raise a type error if another Seq
        (or Seq like) object with an incompatible alphabet is used:

        >>> Seq("AAA", generic_rna) in my_dna
        Traceback (most recent call last):
           ...
        TypeError: Incompatible alphabets DNAAlphabet() and RNAAlphabet()
        >>> Seq("AAA", generic_protein) in my_dna
        Traceback (most recent call last):
           ...
        TypeError: Incompatible alphabets DNAAlphabet() and ProteinAlphabet()
        """
        # If it has one, check the alphabet:
        sub_str = self._get_seq_str_and_check_alphabet(char)
        return sub_str in str(self)

    def find(self, sub, start=0, end=sys.maxsize):
        """Find method, like that of a python string.

        This behaves like the python string method of the same name.

        Returns an integer, the index of the first occurrence of substring
        argument sub in the (sub)sequence given by [start:end].

        Arguments:
         - sub - a string or another Seq object to look for
         - start - optional integer, slice start
         - end - optional integer, slice end

        Returns -1 if the subsequence is NOT found.

        e.g. Locating the first typical start codon, AUG, in an RNA sequence:

        >>> from Bio.Seq import Seq
        >>> my_rna = Seq("GUCAUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAGUUG")
        >>> my_rna.find("AUG")
        3
        """
        # If it has one, check the alphabet:
        sub_str = self._get_seq_str_and_check_alphabet(sub)
        return str(self).find(sub_str, start, end)

    def rfind(self, sub, start=0, end=sys.maxsize):
        """Find from right method, like that of a python string.

        This behaves like the python string method of the same name.

        Returns an integer, the index of the last (right most) occurrence of
        substring argument sub in the (sub)sequence given by [start:end].

        Arguments:
         - sub - a string or another Seq object to look for
         - start - optional integer, slice start
         - end - optional integer, slice end

        Returns -1 if the subsequence is NOT found.

        e.g. Locating the last typical start codon, AUG, in an RNA sequence:

        >>> from Bio.Seq import Seq
        >>> my_rna = Seq("GUCAUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAGUUG")
        >>> my_rna.rfind("AUG")
        15
        """
        # If it has one, check the alphabet:
        sub_str = self._get_seq_str_and_check_alphabet(sub)
        return str(self).rfind(sub_str, start, end)

    def startswith(self, prefix, start=0, end=sys.maxsize):
        """Return True if the Seq starts with the given prefix, False otherwise.

        This behaves like the python string method of the same name.

        Return True if the sequence starts with the specified prefix
        (a string or another Seq object), False otherwise.
        With optional start, test sequence beginning at that position.
        With optional end, stop comparing sequence at that position.
        prefix can also be a tuple of strings to try.  e.g.

        >>> from Bio.Seq import Seq
        >>> my_rna = Seq("GUCAUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAGUUG")
        >>> my_rna.startswith("GUC")
        True
        >>> my_rna.startswith("AUG")
        False
        >>> my_rna.startswith("AUG", 3)
        True
        >>> my_rna.startswith(("UCC", "UCA", "UCG"), 1)
        True
        """
        # If it has one, check the alphabet:
        if isinstance(prefix, tuple):
            prefix_strs = tuple(self._get_seq_str_and_check_alphabet(p)
                                for p in prefix)
            return str(self).startswith(prefix_strs, start, end)
        else:
            prefix_str = self._get_seq_str_and_check_alphabet(prefix)
            return str(self).startswith(prefix_str, start, end)

    def endswith(self, suffix, start=0, end=sys.maxsize):
        """Return True if the Seq ends with the given suffix, False otherwise.

        This behaves like the python string method of the same name.

        Return True if the sequence ends with the specified suffix
        (a string or another Seq object), False otherwise.
        With optional start, test sequence beginning at that position.
        With optional end, stop comparing sequence at that position.
        suffix can also be a tuple of strings to try.  e.g.

        >>> from Bio.Seq import Seq
        >>> my_rna = Seq("GUCAUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAGUUG")
        >>> my_rna.endswith("UUG")
        True
        >>> my_rna.endswith("AUG")
        False
        >>> my_rna.endswith("AUG", 0, 18)
        True
        >>> my_rna.endswith(("UCC", "UCA", "UUG"))
        True
        """
        # If it has one, check the alphabet:
        if isinstance(suffix, tuple):
            suffix_strs = tuple(self._get_seq_str_and_check_alphabet(p)
                                for p in suffix)
            return str(self).endswith(suffix_strs, start, end)
        else:
            suffix_str = self._get_seq_str_and_check_alphabet(suffix)
            return str(self).endswith(suffix_str, start, end)

    def split(self, sep=None, maxsplit=-1):
        """Split method, like that of a python string.

        This behaves like the python string method of the same name.

        Return a list of the 'words' in the string (as Seq objects),
        using sep as the delimiter string.  If maxsplit is given, at
        most maxsplit splits are done.  If maxsplit is omitted, all
        splits are made.

        Following the python string method, sep will by default be any
        white space (tabs, spaces, newlines) but this is unlikely to
        apply to biological sequences.

        e.g.

        >>> from Bio.Seq import Seq
        >>> my_rna = Seq("GUCAUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAGUUG")
        >>> my_aa = my_rna.translate()
        >>> my_aa
        Seq('VMAIVMGR*KGAR*L', HasStopCodon(ExtendedIUPACProtein(), '*'))
        >>> for pep in my_aa.split("*"):
        ...     pep
        Seq('VMAIVMGR', HasStopCodon(ExtendedIUPACProtein(), '*'))
        Seq('KGAR', HasStopCodon(ExtendedIUPACProtein(), '*'))
        Seq('L', HasStopCodon(ExtendedIUPACProtein(), '*'))
        >>> for pep in my_aa.split("*", 1):
        ...     pep
        Seq('VMAIVMGR', HasStopCodon(ExtendedIUPACProtein(), '*'))
        Seq('KGAR*L', HasStopCodon(ExtendedIUPACProtein(), '*'))

        See also the rsplit method:

        >>> for pep in my_aa.rsplit("*", 1):
        ...     pep
        Seq('VMAIVMGR*KGAR', HasStopCodon(ExtendedIUPACProtein(), '*'))
        Seq('L', HasStopCodon(ExtendedIUPACProtein(), '*'))
        """
        # If it has one, check the alphabet:
        sep_str = self._get_seq_str_and_check_alphabet(sep)
        # TODO - If the sep is the defined stop symbol, or gap char,
        # should we adjust the alphabet?
        return [Seq(part, self.alphabet)
                for part in str(self).split(sep_str, maxsplit)]

    def rsplit(self, sep=None, maxsplit=-1):
        """Do a right split method, like that of a python string.

        This behaves like the python string method of the same name.

        Return a list of the 'words' in the string (as Seq objects),
        using sep as the delimiter string.  If maxsplit is given, at
        most maxsplit splits are done COUNTING FROM THE RIGHT.
        If maxsplit is omitted, all splits are made.

        Following the python string method, sep will by default be any
        white space (tabs, spaces, newlines) but this is unlikely to
        apply to biological sequences.

        e.g. print(my_seq.rsplit("*",1))

        See also the split method.
        """
        # If it has one, check the alphabet:
        sep_str = self._get_seq_str_and_check_alphabet(sep)
        return [Seq(part, self.alphabet)
                for part in str(self).rsplit(sep_str, maxsplit)]

    def strip(self, chars=None):
        """Return a new Seq object with leading and trailing ends stripped.

        This behaves like the python string method of the same name.

        Optional argument chars defines which characters to remove.  If
        omitted or None (default) then as for the python string method,
        this defaults to removing any white space.

        e.g. print(my_seq.strip("-"))

        See also the lstrip and rstrip methods.
        """
        # If it has one, check the alphabet:
        strip_str = self._get_seq_str_and_check_alphabet(chars)
        return Seq(str(self).strip(strip_str), self.alphabet)

    def lstrip(self, chars=None):
        """Return a new Seq object with leading (left) end stripped.

        This behaves like the python string method of the same name.

        Optional argument chars defines which characters to remove.  If
        omitted or None (default) then as for the python string method,
        this defaults to removing any white space.

        e.g. print(my_seq.lstrip("-"))

        See also the strip and rstrip methods.
        """
        # If it has one, check the alphabet:
        strip_str = self._get_seq_str_and_check_alphabet(chars)
        return Seq(str(self).lstrip(strip_str), self.alphabet)

    def rstrip(self, chars=None):
        """Return a new Seq object with trailing (right) end stripped.

        This behaves like the python string method of the same name.

        Optional argument chars defines which characters to remove.  If
        omitted or None (default) then as for the python string method,
        this defaults to removing any white space.

        e.g. Removing a nucleotide sequence's polyadenylation (poly-A tail):

        >>> from Bio.Alphabet import IUPAC
        >>> from Bio.Seq import Seq
        >>> my_seq = Seq("CGGTACGCTTATGTCACGTAGAAAAAA", IUPAC.unambiguous_dna)
        >>> my_seq
        Seq('CGGTACGCTTATGTCACGTAGAAAAAA', IUPACUnambiguousDNA())
        >>> my_seq.rstrip("A")
        Seq('CGGTACGCTTATGTCACGTAG', IUPACUnambiguousDNA())

        See also the strip and lstrip methods.
        """
        # If it has one, check the alphabet:
        strip_str = self._get_seq_str_and_check_alphabet(chars)
        return Seq(str(self).rstrip(strip_str), self.alphabet)

    def upper(self):
        """Return an upper case copy of the sequence.

        >>> from Bio.Alphabet import HasStopCodon, generic_protein
        >>> from Bio.Seq import Seq
        >>> my_seq = Seq("VHLTPeeK*", HasStopCodon(generic_protein))
        >>> my_seq
        Seq('VHLTPeeK*', HasStopCodon(ProteinAlphabet(), '*'))
        >>> my_seq.lower()
        Seq('vhltpeek*', HasStopCodon(ProteinAlphabet(), '*'))
        >>> my_seq.upper()
        Seq('VHLTPEEK*', HasStopCodon(ProteinAlphabet(), '*'))

        This will adjust the alphabet if required. See also the lower method.
        """
        return Seq(str(self).upper(), self.alphabet._upper())

    def lower(self):
        """Return a lower case copy of the sequence.

        This will adjust the alphabet if required. Note that the IUPAC
        alphabets are upper case only, and thus a generic alphabet must be
        substituted.

        >>> from Bio.Alphabet import Gapped, generic_dna
        >>> from Bio.Alphabet import IUPAC
        >>> from Bio.Seq import Seq
        >>> my_seq = Seq("CGGTACGCTTATGTCACGTAG*AAAAAA",
        ...          Gapped(IUPAC.unambiguous_dna, "*"))
        >>> my_seq
        Seq('CGGTACGCTTATGTCACGTAG*AAAAAA', Gapped(IUPACUnambiguousDNA(), '*'))
        >>> my_seq.lower()
        Seq('cggtacgcttatgtcacgtag*aaaaaa', Gapped(DNAAlphabet(), '*'))

        See also the upper method.
        """
        return Seq(str(self).lower(), self.alphabet._lower())

    def complement(self):
        """Return the complement sequence by creating a new Seq object.

        >>> from Bio.Seq import Seq
        >>> from Bio.Alphabet import IUPAC
        >>> my_dna = Seq("CCCCCGATAG", IUPAC.unambiguous_dna)
        >>> my_dna
        Seq('CCCCCGATAG', IUPACUnambiguousDNA())
        >>> my_dna.complement()
        Seq('GGGGGCTATC', IUPACUnambiguousDNA())

        You can of course used mixed case sequences,

        >>> from Bio.Seq import Seq
        >>> from Bio.Alphabet import generic_dna
        >>> my_dna = Seq("CCCCCgatA-GD", generic_dna)
        >>> my_dna
        Seq('CCCCCgatA-GD', DNAAlphabet())
        >>> my_dna.complement()
        Seq('GGGGGctaT-CH', DNAAlphabet())

        Note in the above example, ambiguous character D denotes
        G, A or T so its complement is H (for C, T or A).

        Trying to complement a protein sequence raises an exception.

        >>> my_protein = Seq("MAIVMGR", IUPAC.protein)
        >>> my_protein.complement()
        Traceback (most recent call last):
           ...
        ValueError: Proteins do not have complements!
        """
        base = Alphabet._get_base_alphabet(self.alphabet)
        if isinstance(base, Alphabet.ProteinAlphabet):
            raise ValueError("Proteins do not have complements!")
        if isinstance(base, Alphabet.DNAAlphabet):
            ttable = _dna_complement_table
        elif isinstance(base, Alphabet.RNAAlphabet):
            ttable = _rna_complement_table
        elif ('U' in self._data or 'u' in self._data) \
                and ('T' in self._data or 't' in self._data):
            # TODO - Handle this cleanly?
            raise ValueError("Mixed RNA/DNA found")
        elif 'U' in self._data or 'u' in self._data:
            ttable = _rna_complement_table
        else:
            ttable = _dna_complement_table
        # Much faster on really long sequences than the previous loop based
        # one. Thanks to Michael Palmer, University of Waterloo.
        return Seq(str(self).translate(ttable), self.alphabet)

    def reverse_complement(self):
        """Return the reverse complement sequence by creating a new Seq object.

        >>> from Bio.Seq import Seq
        >>> from Bio.Alphabet import IUPAC
        >>> my_dna = Seq("CCCCCGATAGNR", IUPAC.ambiguous_dna)
        >>> my_dna
        Seq('CCCCCGATAGNR', IUPACAmbiguousDNA())
        >>> my_dna.reverse_complement()
        Seq('YNCTATCGGGGG', IUPACAmbiguousDNA())

        Note in the above example, since R = G or A, its complement
        is Y (which denotes C or T).

        You can of course used mixed case sequences,

        >>> from Bio.Seq import Seq
        >>> from Bio.Alphabet import generic_dna
        >>> my_dna = Seq("CCCCCgatA-G", generic_dna)
        >>> my_dna
        Seq('CCCCCgatA-G', DNAAlphabet())
        >>> my_dna.reverse_complement()
        Seq('C-TatcGGGGG', DNAAlphabet())

        Trying to complement a protein sequence raises an exception:

        >>> my_protein = Seq("MAIVMGR", IUPAC.protein)
        >>> my_protein.reverse_complement()
        Traceback (most recent call last):
           ...
        ValueError: Proteins do not have complements!
        """
        # Use -1 stride/step to reverse the complement
        return self.complement()[::-1]

    def transcribe(self):
        """Return the RNA sequence from a DNA sequence by creating a new Seq object.

        >>> from Bio.Seq import Seq
        >>> from Bio.Alphabet import IUPAC
        >>> coding_dna = Seq("ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG",
        ...                  IUPAC.unambiguous_dna)
        >>> coding_dna
        Seq('ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG', IUPACUnambiguousDNA())
        >>> coding_dna.transcribe()
        Seq('AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG', IUPACUnambiguousRNA())

        Trying to transcribe a protein or RNA sequence raises an exception:

        >>> my_protein = Seq("MAIVMGR", IUPAC.protein)
        >>> my_protein.transcribe()
        Traceback (most recent call last):
           ...
        ValueError: Proteins cannot be transcribed!
        """
        base = Alphabet._get_base_alphabet(self.alphabet)
        if isinstance(base, Alphabet.ProteinAlphabet):
            raise ValueError("Proteins cannot be transcribed!")
        if isinstance(base, Alphabet.RNAAlphabet):
            raise ValueError("RNA cannot be transcribed!")

        if self.alphabet == IUPAC.unambiguous_dna:
            alphabet = IUPAC.unambiguous_rna
        elif self.alphabet == IUPAC.ambiguous_dna:
            alphabet = IUPAC.ambiguous_rna
        else:
            alphabet = Alphabet.generic_rna
        return Seq(str(self).replace('T', 'U').replace('t', 'u'), alphabet)

    def back_transcribe(self):
        """Return the DNA sequence from an RNA sequence by creating a new Seq object.

        >>> from Bio.Seq import Seq
        >>> from Bio.Alphabet import IUPAC
        >>> messenger_rna = Seq("AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG",
        ...                     IUPAC.unambiguous_rna)
        >>> messenger_rna
        Seq('AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG', IUPACUnambiguousRNA())
        >>> messenger_rna.back_transcribe()
        Seq('ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG', IUPACUnambiguousDNA())

        Trying to back-transcribe a protein or DNA sequence raises an
        exception:

        >>> my_protein = Seq("MAIVMGR", IUPAC.protein)
        >>> my_protein.back_transcribe()
        Traceback (most recent call last):
           ...
        ValueError: Proteins cannot be back transcribed!
        """
        base = Alphabet._get_base_alphabet(self.alphabet)
        if isinstance(base, Alphabet.ProteinAlphabet):
            raise ValueError("Proteins cannot be back transcribed!")
        if isinstance(base, Alphabet.DNAAlphabet):
            raise ValueError("DNA cannot be back transcribed!")

        if self.alphabet == IUPAC.unambiguous_rna:
            alphabet = IUPAC.unambiguous_dna
        elif self.alphabet == IUPAC.ambiguous_rna:
            alphabet = IUPAC.ambiguous_dna
        else:
            alphabet = Alphabet.generic_dna
        return Seq(str(self).replace("U", "T").replace("u", "t"), alphabet)

    def translate(self, table="Standard", stop_symbol="*", to_stop=False,
                  cds=False, gap=None):
        """Turn a nucleotide sequence into a protein sequence by creating a new Seq object.

        This method will translate DNA or RNA sequences, and those with a
        nucleotide or generic alphabet.  Trying to translate a protein
        sequence raises an exception.

        Arguments:
         - table - Which codon table to use?  This can be either a name
           (string), an NCBI identifier (integer), or a CodonTable
           object (useful for non-standard genetic codes).  This
           defaults to the "Standard" table.
         - stop_symbol - Single character string, what to use for
           terminators.  This defaults to the asterisk, "*".
         - to_stop - Boolean, defaults to False meaning do a full
           translation continuing on past any stop codons (translated as the
           specified stop_symbol).  If True, translation is terminated at
           the first in frame stop codon (and the stop_symbol is not
           appended to the returned protein sequence).
         - cds - Boolean, indicates this is a complete CDS.  If True,
           this checks the sequence starts with a valid alternative start
           codon (which will be translated as methionine, M), that the
           sequence length is a multiple of three, and that there is a
           single in frame stop codon at the end (this will be excluded
           from the protein sequence, regardless of the to_stop option).
           If these tests fail, an exception is raised.
         - gap - Single character string to denote symbol used for gaps.
           It will try to guess the gap character from the alphabet.

        e.g. Using the standard table:

        >>> coding_dna = Seq("GTGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG")
        >>> coding_dna.translate()
        Seq('VAIVMGR*KGAR*', HasStopCodon(ExtendedIUPACProtein(), '*'))
        >>> coding_dna.translate(stop_symbol="@")
        Seq('VAIVMGR@KGAR@', HasStopCodon(ExtendedIUPACProtein(), '@'))
        >>> coding_dna.translate(to_stop=True)
        Seq('VAIVMGR', ExtendedIUPACProtein())

        Now using NCBI table 2, where TGA is not a stop codon:

        >>> coding_dna.translate(table=2)
        Seq('VAIVMGRWKGAR*', HasStopCodon(ExtendedIUPACProtein(), '*'))
        >>> coding_dna.translate(table=2, to_stop=True)
        Seq('VAIVMGRWKGAR', ExtendedIUPACProtein())

        In fact, GTG is an alternative start codon under NCBI table 2, meaning
        this sequence could be a complete CDS:

        >>> coding_dna.translate(table=2, cds=True)
        Seq('MAIVMGRWKGAR', ExtendedIUPACProtein())

        It isn't a valid CDS under NCBI table 1, due to both the start codon
        and also the in frame stop codons:

        >>> coding_dna.translate(table=1, cds=True)
        Traceback (most recent call last):
            ...
        Bio.Data.CodonTable.TranslationError: First codon 'GTG' is not a start codon

        If the sequence has no in-frame stop codon, then the to_stop argument
        has no effect:

        >>> coding_dna2 = Seq("TTGGCCATTGTAATGGGCCGC")
        >>> coding_dna2.translate()
        Seq('LAIVMGR', ExtendedIUPACProtein())
        >>> coding_dna2.translate(to_stop=True)
        Seq('LAIVMGR', ExtendedIUPACProtein())

        When translating gapped sequences, the gap character is inferred from
        the alphabet:

        >>> from Bio.Alphabet import Gapped
        >>> coding_dna3 = Seq("GTG---GCCATT", Gapped(IUPAC.unambiguous_dna))
        >>> coding_dna3.translate()
        Seq('V-AI', Gapped(ExtendedIUPACProtein(), '-'))

        It is possible to pass the gap character when the alphabet is missing:

        >>> coding_dna4 = Seq("GTG---GCCATT")
        >>> coding_dna4.translate(gap='-')
        Seq('V-AI', Gapped(ExtendedIUPACProtein(), '-'))

        NOTE - Ambiguous codons like "TAN" or "NNN" could be an amino acid
        or a stop codon.  These are translated as "X".  Any invalid codon
        (e.g. "TA?" or "T-A") will throw a TranslationError.

        NOTE - This does NOT behave like the python string's translate
        method.  For that use str(my_seq).translate(...) instead.
        """
        if isinstance(table, str) and len(table) == 256:
            raise ValueError("The Seq object translate method DOES NOT take "
                             "a 256 character string mapping table like "
                             "the python string object's translate method. "
                             "Use str(my_seq).translate(...) instead.")
        if isinstance(Alphabet._get_base_alphabet(self.alphabet),
                      Alphabet.ProteinAlphabet):
            raise ValueError("Proteins cannot be translated!")
        try:
            table_id = int(table)
        except ValueError:
            # Assume its a table name
            if self.alphabet == IUPAC.unambiguous_dna:
                # Will use standard IUPAC protein alphabet, no need for X
                codon_table = CodonTable.unambiguous_dna_by_name[table]
            elif self.alphabet == IUPAC.unambiguous_rna:
                # Will use standard IUPAC protein alphabet, no need for X
                codon_table = CodonTable.unambiguous_rna_by_name[table]
            else:
                # This will use the extended IUPAC protein alphabet with X etc.
                # The same table can be used for RNA or DNA (we use this for
                # translating strings).
                codon_table = CodonTable.ambiguous_generic_by_name[table]
        except (AttributeError, TypeError):
            # Assume its a CodonTable object
            if isinstance(table, CodonTable.CodonTable):
                codon_table = table
            else:
                raise ValueError('Bad table argument')
        else:
            # Assume its a table ID
            if self.alphabet == IUPAC.unambiguous_dna:
                # Will use standard IUPAC protein alphabet, no need for X
                codon_table = CodonTable.unambiguous_dna_by_id[table_id]
            elif self.alphabet == IUPAC.unambiguous_rna:
                # Will use standard IUPAC protein alphabet, no need for X
                codon_table = CodonTable.unambiguous_rna_by_id[table_id]
            else:
                # This will use the extended IUPAC protein alphabet with X etc.
                # The same table can be used for RNA or DNA (we use this for
                # translating strings).
                codon_table = CodonTable.ambiguous_generic_by_id[table_id]

        # Deal with gaps for translation
        if hasattr(self.alphabet, "gap_char"):
            if not gap:
                gap = self.alphabet.gap_char
            elif gap != self.alphabet.gap_char:
                raise ValueError(
                    "Gap {0!r} does not match {1!r} from alphabet".format(
                        gap, self.alphabet.gap_char))

        protein = _translate_str(str(self), codon_table, stop_symbol, to_stop,
                                 cds, gap=gap)

        if gap and gap in protein:
            alphabet = Alphabet.Gapped(codon_table.protein_alphabet, gap)
        else:
            alphabet = codon_table.protein_alphabet

        if stop_symbol in protein:
            alphabet = Alphabet.HasStopCodon(alphabet, stop_symbol)

        return Seq(protein, alphabet)

    def ungap(self, gap=None):
        """Return a copy of the sequence without the gap character(s).

        The gap character can be specified in two ways - either as an explicit
        argument, or via the sequence's alphabet. For example:

        >>> from Bio.Seq import Seq
        >>> from Bio.Alphabet import generic_dna
        >>> my_dna = Seq("-ATA--TGAAAT-TTGAAAA", generic_dna)
        >>> my_dna
        Seq('-ATA--TGAAAT-TTGAAAA', DNAAlphabet())
        >>> my_dna.ungap("-")
        Seq('ATATGAAATTTGAAAA', DNAAlphabet())

        If the gap character is not given as an argument, it will be taken from
        the sequence's alphabet (if defined). Notice that the returned
        sequence's alphabet is adjusted since it no longer requires a gapped
        alphabet:

        >>> from Bio.Seq import Seq
        >>> from Bio.Alphabet import IUPAC, Gapped, HasStopCodon
        >>> my_pro = Seq("MVVLE=AD*", HasStopCodon(Gapped(IUPAC.protein, "=")))
        >>> my_pro
        Seq('MVVLE=AD*', HasStopCodon(Gapped(IUPACProtein(), '='), '*'))
        >>> my_pro.ungap()
        Seq('MVVLEAD*', HasStopCodon(IUPACProtein(), '*'))

        Or, with a simpler gapped DNA example:

        >>> from Bio.Seq import Seq
        >>> from Bio.Alphabet import IUPAC, Gapped
        >>> my_seq = Seq("CGGGTAG=AAAAAA", Gapped(IUPAC.unambiguous_dna, "="))
        >>> my_seq
        Seq('CGGGTAG=AAAAAA', Gapped(IUPACUnambiguousDNA(), '='))
        >>> my_seq.ungap()
        Seq('CGGGTAGAAAAAA', IUPACUnambiguousDNA())

        As long as it is consistent with the alphabet, although it is
        redundant, you can still supply the gap character as an argument to
        this method:

        >>> my_seq
        Seq('CGGGTAG=AAAAAA', Gapped(IUPACUnambiguousDNA(), '='))
        >>> my_seq.ungap("=")
        Seq('CGGGTAGAAAAAA', IUPACUnambiguousDNA())

        However, if the gap character given as the argument disagrees with that
        declared in the alphabet, an exception is raised:

        >>> my_seq
        Seq('CGGGTAG=AAAAAA', Gapped(IUPACUnambiguousDNA(), '='))
        >>> my_seq.ungap("-")
        Traceback (most recent call last):
           ...
        ValueError: Gap '-' does not match '=' from alphabet

        Finally, if a gap character is not supplied, and the alphabet does not
        define one, an exception is raised:

        >>> from Bio.Seq import Seq
        >>> from Bio.Alphabet import generic_dna
        >>> my_dna = Seq("ATA--TGAAAT-TTGAAAA", generic_dna)
        >>> my_dna
        Seq('ATA--TGAAAT-TTGAAAA', DNAAlphabet())
        >>> my_dna.ungap()
        Traceback (most recent call last):
           ...
        ValueError: Gap character not given and not defined in alphabet

        """
        if hasattr(self.alphabet, "gap_char"):
            if not gap:
                gap = self.alphabet.gap_char
            elif gap != self.alphabet.gap_char:
                raise ValueError(
                    "Gap {0!r} does not match {1!r} from alphabet".format(
                        gap, self.alphabet.gap_char))
            alpha = Alphabet._ungap(self.alphabet)
        elif not gap:
            raise ValueError("Gap character not given and not defined in "
                             "alphabet")
        else:
            alpha = self.alphabet  # modify!
        if len(gap) != 1 or not isinstance(gap, str):
            raise ValueError("Unexpected gap character, {0!r}".format(gap))
        return Seq(str(self).replace(gap, ""), alpha)


class UnknownSeq(Seq):
    """Read-only sequence object of known length but unknown contents.

    If you have an unknown sequence, you can represent this with a normal
    Seq object, for example:

    >>> my_seq = Seq("N"*5)
    >>> my_seq
    Seq('NNNNN')
    >>> len(my_seq)
    5
    >>> print(my_seq)
    NNNNN

    However, this is rather wasteful of memory (especially for large
    sequences), which is where this class is most useful:

    >>> unk_five = UnknownSeq(5)
    >>> unk_five
    UnknownSeq(5, character='?')
    >>> len(unk_five)
    5
    >>> print(unk_five)
    ?????

    You can add unknown sequence together, provided their alphabets and
    characters are compatible, and get another memory saving UnknownSeq:

    >>> unk_four = UnknownSeq(4)
    >>> unk_four
    UnknownSeq(4, character='?')
    >>> unk_four + unk_five
    UnknownSeq(9, character='?')

    If the alphabet or characters don't match up, the addition gives an
    ordinary Seq object:

    >>> unk_nnnn = UnknownSeq(4, character="N")
    >>> unk_nnnn
    UnknownSeq(4, character='N')
    >>> unk_nnnn + unk_four
    Seq('NNNN????')

    Combining with a real Seq gives a new Seq object:

    >>> known_seq = Seq("ACGT")
    >>> unk_four + known_seq
    Seq('????ACGT')
    >>> known_seq + unk_four
    Seq('ACGT????')
    """

    def __init__(self, length, alphabet=Alphabet.generic_alphabet,
                 character=None):
        """Create a new UnknownSeq object.

        If character is omitted, it is determined from the alphabet, "N" for
        nucleotides, "X" for proteins, and "?" otherwise.
        """
        self._length = int(length)
        if self._length < 0:
            # TODO - Block zero length UnknownSeq?  You can just use a Seq!
            raise ValueError("Length must not be negative.")
        self.alphabet = alphabet
        if character:
            if len(character) != 1:
                raise ValueError("character argument should be a single "
                                 "letter string.")
            self._character = character
        else:
            base = Alphabet._get_base_alphabet(alphabet)
            # TODO? Check the case of the letters in the alphabet?
            # We may have to use "n" instead of "N" etc.
            if isinstance(base, Alphabet.NucleotideAlphabet):
                self._character = "N"
            elif isinstance(base, Alphabet.ProteinAlphabet):
                self._character = "X"
            else:
                self._character = "?"

    def __len__(self):
        """Return the stated length of the unknown sequence."""
        return self._length

    def __str__(self):
        """Return the unknown sequence as full string of the given length."""
        return self._character * self._length

    def __repr__(self):
        """Return (truncated) representation of the sequence for debugging."""
        if self.alphabet is Alphabet.generic_alphabet:
            # Default used, we can omit it and simplify the representation
            a = ""
        else:
            a = ", alphabet=%r" % self.alphabet
        return "UnknownSeq({0}{1!s}, character={2!r})".format(
            self._length, a, self._character)

    def __add__(self, other):
        """Add another sequence or string to this sequence.

        Adding two UnknownSeq objects returns another UnknownSeq object
        provided the character is the same and the alphabets are compatible.

        >>> from Bio.Seq import UnknownSeq
        >>> from Bio.Alphabet import generic_protein
        >>> UnknownSeq(10, generic_protein) + UnknownSeq(5, generic_protein)
        UnknownSeq(15, alphabet=ProteinAlphabet(), character='X')

        If the characters differ, an UnknownSeq object cannot be used, so a
        Seq object is returned:

        >>> from Bio.Seq import UnknownSeq
        >>> from Bio.Alphabet import generic_protein
        >>> UnknownSeq(10, generic_protein) + UnknownSeq(5, generic_protein,
        ...                                              character="x")
        Seq('XXXXXXXXXXxxxxx', ProteinAlphabet())

        If adding a string to an UnknownSeq, a new Seq is returned with the
        same alphabet:

        >>> from Bio.Seq import UnknownSeq
        >>> from Bio.Alphabet import generic_protein
        >>> UnknownSeq(5, generic_protein) + "LV"
        Seq('XXXXXLV', ProteinAlphabet())
        """
        if isinstance(other, UnknownSeq) and \
           other._character == self._character:
            # TODO - Check the alphabets match
            return UnknownSeq(len(self) + len(other),
                              self.alphabet, self._character)
        # Offload to the base class...
        return Seq(str(self), self.alphabet) + other

    def __radd__(self, other):
        """Add a sequence on the left."""
        # If other is an UnknownSeq, then __add__ would be called.
        # Offload to the base class...
        return other + Seq(str(self), self.alphabet)

    def __mul__(self, other):
        """Multiply UnknownSeq by integer.

        >>> from Bio.Seq import UnknownSeq
        >>> from Bio.Alphabet import generic_dna
        >>> UnknownSeq(3) * 2
        UnknownSeq(6, character='?')
        >>> UnknownSeq(3, generic_dna) * 2
        UnknownSeq(6, alphabet=DNAAlphabet(), character='N')
        """
        if not isinstance(other, int):
            raise TypeError("can't multiply {} by non-int type".format(self.__class__.__name__))
        return self.__class__(len(self) * other, self.alphabet)

    def __rmul__(self, other):
        """Multiply integer by UnknownSeq.

        >>> from Bio.Seq import UnknownSeq
        >>> from Bio.Alphabet import generic_dna
        >>> 2 * UnknownSeq(3)
        UnknownSeq(6, character='?')
        >>> 2 * UnknownSeq(3, generic_dna)
        UnknownSeq(6, alphabet=DNAAlphabet(), character='N')
        """
        if not isinstance(other, int):
            raise TypeError("can't multiply {} by non-int type".format(self.__class__.__name__))
        return self.__class__(len(self) * other, self.alphabet)

    def __imul__(self, other):
        """Multiply UnknownSeq in-place.

        Note although UnknownSeq is immutable, the in-place method is
        included to match the behaviour for regular Python strings.

        >>> from Bio.Seq import UnknownSeq
        >>> from Bio.Alphabet import generic_dna
        >>> seq = UnknownSeq(3, generic_dna)
        >>> seq *= 2
        >>> seq
        UnknownSeq(6, alphabet=DNAAlphabet(), character='N')
        """
        if not isinstance(other, int):
            raise TypeError("can't multiply {} by non-int type".format(self.__class__.__name__))
        return self.__class__(len(self) * other, self.alphabet)

    def __getitem__(self, index):
        """Get a subsequence from the UnknownSeq object.

        >>> unk = UnknownSeq(8, character="N")
        >>> print(unk[:])
        NNNNNNNN
        >>> print(unk[5:3])
        <BLANKLINE>
        >>> print(unk[1:-1])
        NNNNNN
        >>> print(unk[1:-1:2])
        NNN
        """
        if isinstance(index, int):
            # TODO - Check the bounds without wasting memory
            return str(self)[index]
        old_length = self._length
        step = index.step
        if step is None or step == 1:
            # This calculates the length you'd get from ("N"*old_length)[index]
            start = index.start
            end = index.stop
            if start is None:
                start = 0
            elif start < 0:
                start = max(0, old_length + start)
            elif start > old_length:
                start = old_length
            if end is None:
                end = old_length
            elif end < 0:
                end = max(0, old_length + end)
            elif end > old_length:
                end = old_length
            new_length = max(0, end - start)
        elif step == 0:
            raise ValueError("slice step cannot be zero")
        else:
            # TODO - handle step efficiently
            new_length = len(("X" * old_length)[index])
        # assert new_length == len(("X"*old_length)[index]), \
        #       (index, start, end, step, old_length,
        #        new_length, len(("X"*old_length)[index]))
        return UnknownSeq(new_length, self.alphabet, self._character)

    def count(self, sub, start=0, end=sys.maxsize):
        """Return a non-overlapping count, like that of a python string.

        This behaves like the python string (and Seq object) method of the
        same name, which does a non-overlapping count!

        For an overlapping search use the newer count_overlap() method.

        Returns an integer, the number of occurrences of substring
        argument sub in the (sub)sequence given by [start:end].
        Optional arguments start and end are interpreted as in slice
        notation.

        Arguments:
         - sub - a string or another Seq object to look for
         - start - optional integer, slice start
         - end - optional integer, slice end

        >>> "NNNN".count("N")
        4
        >>> Seq("NNNN").count("N")
        4
        >>> UnknownSeq(4, character="N").count("N")
        4
        >>> UnknownSeq(4, character="N").count("A")
        0
        >>> UnknownSeq(4, character="N").count("AA")
        0

        HOWEVER, please note because that python strings and Seq objects (and
        MutableSeq objects) do a non-overlapping search, this may not give
        the answer you expect:

        >>> UnknownSeq(4, character="N").count("NN")
        2
        >>> UnknownSeq(4, character="N").count("NNN")
        1
        """
        sub_str = self._get_seq_str_and_check_alphabet(sub)
        len_self, len_sub_str = self._length, len(sub_str)
        # Handling case where substring not in self
        if set(sub_str) != set(self._character):
            return 0
        # Setting None to the default arguments
        if start is None:
            start = 0
        if end is None:
            end = sys.maxsize
        # Truncating start and end to max of self._length and min of -self._length
        start = max(min(start, len_self), -len_self)
        end = max(min(end, len_self), -len_self)
        # Convert start and ends to positive indexes
        if start < 0:
            start += len_self
        if end < 0:
            end += len_self
        # Handle case where end <= start (no negative step argument here)
        # and case where len_sub_str is larger than the search space
        if end <= start or (end - start) < len_sub_str:
            return 0
        # 'Normal' calculation
        return (end - start) // len_sub_str

    def count_overlap(self, sub, start=0, end=sys.maxsize):
        """Return an overlapping count.

        For a non-overlapping search use the count() method.

        Returns an integer, the number of occurrences of substring
        argument sub in the (sub)sequence given by [start:end].
        Optional arguments start and end are interpreted as in slice
        notation.

        Arguments:
         - sub - a string or another Seq object to look for
         - start - optional integer, slice start
         - end - optional integer, slice end

        e.g.

        >>> from Bio.Seq import UnknownSeq
        >>> UnknownSeq(4, character="N").count_overlap("NN")
        3
        >>> UnknownSeq(4, character="N").count_overlap("NNN")
        2

        Where substrings do not overlap, should behave the same as
        the count() method:

        >>> UnknownSeq(4, character="N").count_overlap("N")
        4
        >>> UnknownSeq(4, character="N").count_overlap("N") == UnknownSeq(4, character="N").count("N")
        True
        >>> UnknownSeq(4, character="N").count_overlap("A")
        0
        >>> UnknownSeq(4, character="N").count_overlap("A") == UnknownSeq(4, character="N").count("A")
        True
        >>> UnknownSeq(4, character="N").count_overlap("AA")
        0
        >>> UnknownSeq(4, character="N").count_overlap("AA") == UnknownSeq(4, character="N").count("AA")
        True
        """
        sub_str = self._get_seq_str_and_check_alphabet(sub)
        len_self, len_sub_str = self._length, len(sub_str)
        # Handling case where substring not in self
        if set(sub_str) != set(self._character):
            return 0
        # Setting None to the default arguments
        if start is None:
            start = 0
        if end is None:
            end = sys.maxsize
        # Truncating start and end to max of self._length and min of -self._length
        start = max(min(start, len_self), -len_self)
        end = max(min(end, len_self), -len_self)
        # Convert start and ends to positive indexes
        if start < 0:
            start += len_self
        if end < 0:
            end += len_self
        # Handle case where end <= start (no negative step argument here)
        # and case where len_sub_str is larger than the search space
        if end <= start or (end - start) < len_sub_str:
            return 0
        # 'Normal' calculation
        return end - start - len_sub_str + 1

    def complement(self):
        """Return the complement of an unknown nucleotide equals itself.

        >>> my_nuc = UnknownSeq(8)
        >>> my_nuc
        UnknownSeq(8, character='?')
        >>> print(my_nuc)
        ????????
        >>> my_nuc.complement()
        UnknownSeq(8, character='?')
        >>> print(my_nuc.complement())
        ????????
        """
        if isinstance(Alphabet._get_base_alphabet(self.alphabet),
                      Alphabet.ProteinAlphabet):
            raise ValueError("Proteins do not have complements!")
        return self

    def reverse_complement(self):
        """Return the reverse complement of an unknown sequence.

        The reverse complement of an unknown nucleotide equals itself:

        >>> from Bio.Seq import UnknownSeq
        >>> from Bio.Alphabet import generic_dna
        >>> example = UnknownSeq(6, generic_dna)
        >>> print(example)
        NNNNNN
        >>> print(example.reverse_complement())
        NNNNNN
        """
        if isinstance(Alphabet._get_base_alphabet(self.alphabet),
                      Alphabet.ProteinAlphabet):
            raise ValueError("Proteins do not have complements!")
        return self

    def transcribe(self):
        """Return an unknown RNA sequence from an unknown DNA sequence.

        >>> my_dna = UnknownSeq(10, character="N")
        >>> my_dna
        UnknownSeq(10, character='N')
        >>> print(my_dna)
        NNNNNNNNNN
        >>> my_rna = my_dna.transcribe()
        >>> my_rna
        UnknownSeq(10, alphabet=RNAAlphabet(), character='N')
        >>> print(my_rna)
        NNNNNNNNNN
        """
        # Offload the alphabet stuff
        s = Seq(self._character, self.alphabet).transcribe()
        return UnknownSeq(self._length, s.alphabet, self._character)

    def back_transcribe(self):
        """Return an unknown DNA sequence from an unknown RNA sequence.

        >>> my_rna = UnknownSeq(20, character="N")
        >>> my_rna
        UnknownSeq(20, character='N')
        >>> print(my_rna)
        NNNNNNNNNNNNNNNNNNNN
        >>> my_dna = my_rna.back_transcribe()
        >>> my_dna
        UnknownSeq(20, alphabet=DNAAlphabet(), character='N')
        >>> print(my_dna)
        NNNNNNNNNNNNNNNNNNNN
        """
        # Offload the alphabet stuff
        s = Seq(self._character, self.alphabet).back_transcribe()
        return UnknownSeq(self._length, s.alphabet, self._character)

    def upper(self):
        """Return an upper case copy of the sequence.

        >>> from Bio.Alphabet import generic_dna
        >>> from Bio.Seq import UnknownSeq
        >>> my_seq = UnknownSeq(20, generic_dna, character="n")
        >>> my_seq
        UnknownSeq(20, alphabet=DNAAlphabet(), character='n')
        >>> print(my_seq)
        nnnnnnnnnnnnnnnnnnnn
        >>> my_seq.upper()
        UnknownSeq(20, alphabet=DNAAlphabet(), character='N')
        >>> print(my_seq.upper())
        NNNNNNNNNNNNNNNNNNNN

        This will adjust the alphabet if required. See also the lower method.
        """
        return UnknownSeq(self._length, self.alphabet._upper(),
                          self._character.upper())

    def lower(self):
        """Return a lower case copy of the sequence.

        This will adjust the alphabet if required:

        >>> from Bio.Alphabet import IUPAC
        >>> from Bio.Seq import UnknownSeq
        >>> my_seq = UnknownSeq(20, IUPAC.extended_protein)
        >>> my_seq
        UnknownSeq(20, alphabet=ExtendedIUPACProtein(), character='X')
        >>> print(my_seq)
        XXXXXXXXXXXXXXXXXXXX
        >>> my_seq.lower()
        UnknownSeq(20, alphabet=ProteinAlphabet(), character='x')
        >>> print(my_seq.lower())
        xxxxxxxxxxxxxxxxxxxx

        See also the upper method.
        """
        return UnknownSeq(self._length, self.alphabet._lower(),
                          self._character.lower())

    def translate(self, **kwargs):
        """Translate an unknown nucleotide sequence into an unknown protein.

        e.g.

        >>> my_seq = UnknownSeq(9, character="N")
        >>> print(my_seq)
        NNNNNNNNN
        >>> my_protein = my_seq.translate()
        >>> my_protein
        UnknownSeq(3, alphabet=ProteinAlphabet(), character='X')
        >>> print(my_protein)
        XXX

        In comparison, using a normal Seq object:

        >>> my_seq = Seq("NNNNNNNNN")
        >>> print(my_seq)
        NNNNNNNNN
        >>> my_protein = my_seq.translate()
        >>> my_protein
        Seq('XXX', ExtendedIUPACProtein())
        >>> print(my_protein)
        XXX

        """
        if isinstance(Alphabet._get_base_alphabet(self.alphabet),
                      Alphabet.ProteinAlphabet):
            raise ValueError("Proteins cannot be translated!")
        return UnknownSeq(self._length // 3, Alphabet.generic_protein, "X")

    def ungap(self, gap=None):
        """Return a copy of the sequence without the gap character(s).

        The gap character can be specified in two ways - either as an explicit
        argument, or via the sequence's alphabet. For example:

        >>> from Bio.Seq import UnknownSeq
        >>> from Bio.Alphabet import Gapped, generic_dna
        >>> my_dna = UnknownSeq(20, Gapped(generic_dna, "-"))
        >>> my_dna
        UnknownSeq(20, alphabet=Gapped(DNAAlphabet(), '-'), character='N')
        >>> my_dna.ungap()
        UnknownSeq(20, alphabet=DNAAlphabet(), character='N')
        >>> my_dna.ungap("-")
        UnknownSeq(20, alphabet=DNAAlphabet(), character='N')

        If the UnknownSeq is using the gap character, then an empty Seq is
        returned:

        >>> my_gap = UnknownSeq(20, Gapped(generic_dna, "-"), character="-")
        >>> my_gap
        UnknownSeq(20, alphabet=Gapped(DNAAlphabet(), '-'), character='-')
        >>> my_gap.ungap()
        Seq('', DNAAlphabet())
        >>> my_gap.ungap("-")
        Seq('', DNAAlphabet())

        Notice that the returned sequence's alphabet is adjusted to remove any
        explicit gap character declaration.
        """
        # Offload the alphabet stuff
        s = Seq(self._character, self.alphabet).ungap(gap)
        if s:
            return UnknownSeq(self._length, s.alphabet, self._character)
        else:
            return Seq("", s.alphabet)


class MutableSeq(object):
    """An editable sequence object (with an alphabet).

    Unlike normal python strings and our basic sequence object (the Seq class)
    which are immutable, the MutableSeq lets you edit the sequence in place.
    However, this means you cannot use a MutableSeq object as a dictionary key.

    >>> from Bio.Seq import MutableSeq
    >>> from Bio.Alphabet import generic_dna
    >>> my_seq = MutableSeq("ACTCGTCGTCG", generic_dna)
    >>> my_seq
    MutableSeq('ACTCGTCGTCG', DNAAlphabet())
    >>> my_seq[5]
    'T'
    >>> my_seq[5] = "A"
    >>> my_seq
    MutableSeq('ACTCGACGTCG', DNAAlphabet())
    >>> my_seq[5]
    'A'
    >>> my_seq[5:8] = "NNN"
    >>> my_seq
    MutableSeq('ACTCGNNNTCG', DNAAlphabet())
    >>> len(my_seq)
    11

    Note that the MutableSeq object does not support as many string-like
    or biological methods as the Seq object.
    """

    def __init__(self, data, alphabet=Alphabet.generic_alphabet):
        """Initialize the class."""
        if sys.version_info[0] == 3:
            self.array_indicator = "u"
        else:
            self.array_indicator = "c"
        if isinstance(data, str):  # TODO - What about unicode?
            self.data = array.array(self.array_indicator, data)
        else:
            self.data = data   # assumes the input is an array
        self.alphabet = alphabet

    def __repr__(self):
        """Return (truncated) representation of the sequence for debugging."""
        if self.alphabet is Alphabet.generic_alphabet:
            # Default used, we can omit it and simplify the representation
            a = ""
        else:
            a = ", %r" % self.alphabet
        if len(self) > 60:
            # Shows the last three letters as it is often useful to see if
            # there is a stop codon at the end of a sequence.
            # Note total length is 54+3+3=60
            return "{0}('{1}...{2}'{3!s})".format(self.__class__.__name__,
                                                  str(self[:54]),
                                                  str(self[-3:]),
                                                  a)
        else:
            return "{0}('{1}'{2!s})".format(self.__class__.__name__,
                                            str(self),
                                            a)

    def __str__(self):
        """Return the full sequence as a python string.

        Note that Biopython 1.44 and earlier would give a truncated
        version of repr(my_seq) for str(my_seq).  If you are writing code
        which needs to be backwards compatible with old Biopython, you
        should continue to use my_seq.tostring() rather than str(my_seq).
        """
        # See test_GAQueens.py for an historic usage of a non-string alphabet!
        return "".join(self.data)

    def __eq__(self, other):
        """Compare the sequence to another sequence or a string (README).

        Currently if compared to another sequence the alphabets must be
        compatible. Comparing DNA to RNA, or Nucleotide to Protein will raise
        an exception. Otherwise only the sequence itself is compared, not the
        precise alphabet.

        A future release of Biopython will change this (and the Seq object etc)
        to use simple string comparison. The plan is that comparing sequences
        with incompatible alphabets (e.g. DNA to RNA) will trigger a warning
        but not an exception.

        During this transition period, please just do explicit comparisons:

        >>> seq1 = MutableSeq("ACGT")
        >>> seq2 = MutableSeq("ACGT")
        >>> id(seq1) == id(seq2)
        False
        >>> str(seq1) == str(seq2)
        True

        Biopython now does:

        >>> seq1 == seq2
        True
        >>> seq1 == Seq("ACGT")
        True
        >>> seq1 == "ACGT"
        True

        """
        if hasattr(other, "alphabet"):
            if not Alphabet._check_type_compatible([self.alphabet,
                                                    other.alphabet]):
                warnings.warn("Incompatible alphabets {0!r} and {1!r}".format(
                              self.alphabet, other.alphabet),
                              BiopythonWarning)
            if isinstance(other, MutableSeq):
                return self.data == other.data
        return str(self) == str(other)

    def __ne__(self, other):
        """Implement the not-equal operand."""
        # Seem to require this method for Python 2 but not needed on Python 3?
        return not (self == other)

    def __lt__(self, other):
        """Implement the less-than operand."""
        if hasattr(other, "alphabet"):
            if not Alphabet._check_type_compatible([self.alphabet,
                                                    other.alphabet]):
                warnings.warn("Incompatible alphabets {0!r} and {1!r}".format(
                              self.alphabet, other.alphabet),
                              BiopythonWarning)
            if isinstance(other, MutableSeq):
                return self.data < other.data
        if isinstance(other, (str, Seq, UnknownSeq)):
            return str(self) < str(other)
        raise TypeError("'<' not supported between instances of '{}' and '{}'"
                        .format(type(self).__name__, type(other).__name__))

    def __le__(self, other):
        """Implement the less-than or equal operand."""
        if hasattr(other, "alphabet"):
            if not Alphabet._check_type_compatible([self.alphabet,
                                                    other.alphabet]):
                warnings.warn("Incompatible alphabets {0!r} and {1!r}".format(
                              self.alphabet, other.alphabet),
                              BiopythonWarning)
            if isinstance(other, MutableSeq):
                return self.data <= other.data
        if isinstance(other, (str, Seq, UnknownSeq)):
            return str(self) <= str(other)
        raise TypeError("'<=' not supported between instances of '{}' and '{}'"
                        .format(type(self).__name__, type(other).__name__))

    def __gt__(self, other):
        """Implement the greater-than operand."""
        if hasattr(other, "alphabet"):
            if not Alphabet._check_type_compatible([self.alphabet,
                                                    other.alphabet]):
                warnings.warn("Incompatible alphabets {0!r} and {1!r}".format(
                              self.alphabet, other.alphabet),
                              BiopythonWarning)
            if isinstance(other, MutableSeq):
                return self.data > other.data
        if isinstance(other, (str, Seq, UnknownSeq)):
            return str(self) > str(other)
        raise TypeError("'>' not supported between instances of '{}' and '{}'"
                        .format(type(self).__name__, type(other).__name__))

    def __ge__(self, other):
        """Implement the greater-than or equal operand."""
        if hasattr(other, "alphabet"):
            if not Alphabet._check_type_compatible([self.alphabet,
                                                    other.alphabet]):
                warnings.warn("Incompatible alphabets {0!r} and {1!r}".format(
                              self.alphabet, other.alphabet),
                              BiopythonWarning)
            if isinstance(other, MutableSeq):
                return self.data >= other.data
        if isinstance(other, (str, Seq, UnknownSeq)):
            return str(self) >= str(other)
        raise TypeError("'>=' not supported between instances of '{}' and '{}'"
                        .format(type(self).__name__, type(other).__name__))

    def __len__(self):
        """Return the length of the sequence, use len(my_seq)."""
        return len(self.data)

    def __getitem__(self, index):
        """Return a subsequence of single letter, use my_seq[index].

        >>> my_seq = MutableSeq('ACTCGACGTCG')
        >>> my_seq[5]
        'A'
        """
        # Note since Python 2.0, __getslice__ is deprecated
        # and __getitem__ is used instead.
        # See http://docs.python.org/ref/sequence-methods.html
        if isinstance(index, int):
            # Return a single letter as a string
            return self.data[index]
        else:
            # Return the (sub)sequence as another Seq object
            return MutableSeq(self.data[index], self.alphabet)

    def __setitem__(self, index, value):
        """Set a subsequence of single letter via value parameter.

        >>> my_seq = MutableSeq('ACTCGACGTCG')
        >>> my_seq[0] = 'T'
        >>> my_seq
        MutableSeq('TCTCGACGTCG')
        """
        # Note since Python 2.0, __setslice__ is deprecated
        # and __setitem__ is used instead.
        # See http://docs.python.org/ref/sequence-methods.html
        if isinstance(index, int):
            # Replacing a single letter with a new string
            self.data[index] = value
        else:
            # Replacing a sub-sequence
            if isinstance(value, MutableSeq):
                self.data[index] = value.data
            elif isinstance(value, type(self.data)):
                self.data[index] = value
            else:
                self.data[index] = array.array(self.array_indicator,
                                               str(value))

    def __delitem__(self, index):
        """Delete a subsequence of single letter.

        >>> my_seq = MutableSeq('ACTCGACGTCG')
        >>> del my_seq[0]
        >>> my_seq
        MutableSeq('CTCGACGTCG')
        """
        # Note since Python 2.0, __delslice__ is deprecated
        # and __delitem__ is used instead.
        # See http://docs.python.org/ref/sequence-methods.html

        # Could be deleting a single letter, or a slice
        del self.data[index]

    def __add__(self, other):
        """Add another sequence or string to this sequence.

        Returns a new MutableSeq object.
        """
        if hasattr(other, "alphabet"):
            # other should be a Seq or a MutableSeq
            if not Alphabet._check_type_compatible([self.alphabet,
                                                    other.alphabet]):
                raise TypeError(
                    "Incompatible alphabets {0!r} and {1!r}".format(
                        self.alphabet, other.alphabet))
            # They should be the same sequence type (or one of them is generic)
            a = Alphabet._consensus_alphabet([self.alphabet, other.alphabet])
            if isinstance(other, MutableSeq):
                # See test_GAQueens.py for an historic usage of a non-string
                # alphabet!  Adding the arrays should support this.
                return self.__class__(self.data + other.data, a)
            else:
                return self.__class__(str(self) + str(other), a)
        elif isinstance(other, basestring):
            # other is a plain string - use the current alphabet
            return self.__class__(str(self) + str(other), self.alphabet)
        else:
            raise TypeError

    def __radd__(self, other):
        """Add a sequence on the left.

        >>> from Bio.Seq import MutableSeq
        >>> from Bio.Alphabet import generic_protein
        >>> "LV" + MutableSeq("MELKI", generic_protein)
        MutableSeq('LVMELKI', ProteinAlphabet())
        """
        if hasattr(other, "alphabet"):
            # other should be a Seq or a MutableSeq
            if not Alphabet._check_type_compatible([self.alphabet,
                                                    other.alphabet]):
                raise TypeError(
                    "Incompatible alphabets {0!r} and {1!r}".format(
                        self.alphabet, other.alphabet))
            # They should be the same sequence type (or one of them is generic)
            a = Alphabet._consensus_alphabet([self.alphabet, other.alphabet])
            if isinstance(other, MutableSeq):
                # See test_GAQueens.py for an historic usage of a non-string
                # alphabet!  Adding the arrays should support this.
                return self.__class__(other.data + self.data, a)
            else:
                return self.__class__(str(other) + str(self), a)
        elif isinstance(other, basestring):
            # other is a plain string - use the current alphabet
            return self.__class__(str(other) + str(self), self.alphabet)
        else:
            raise TypeError

    def __mul__(self, other):
        """Multiply MutableSeq by integer.

        Note this is not in-place and returns a new object,
        matching native Python list multiplication.

        >>> from Bio.Seq import MutableSeq
        >>> from Bio.Alphabet import generic_dna
        >>> MutableSeq('ATG') * 2
        MutableSeq('ATGATG')
        >>> MutableSeq('ATG', generic_dna) * 2
        MutableSeq('ATGATG', DNAAlphabet())
        """
        if not isinstance(other, int):
            raise TypeError("can't multiply {} by non-int type".format(self.__class__.__name__))
        return self.__class__(self.data * other, self.alphabet)

    def __rmul__(self, other):
        """Multiply integer by MutableSeq.

        Note this is not in-place and returns a new object,
        matching native Python list multiplication.

        >>> from Bio.Seq import MutableSeq
        >>> from Bio.Alphabet import generic_dna
        >>> 2 * MutableSeq('ATG')
        MutableSeq('ATGATG')
        >>> 2 * MutableSeq('ATG', generic_dna)
        MutableSeq('ATGATG', DNAAlphabet())
        """
        if not isinstance(other, int):
            raise TypeError("can't multiply {} by non-int type".format(self.__class__.__name__))
        return self.__class__(self.data * other, self.alphabet)

    def __imul__(self, other):
        """Multiply MutableSeq in-place.

        >>> from Bio.Seq import MutableSeq
        >>> from Bio.Alphabet import generic_dna
        >>> seq = MutableSeq('ATG', generic_dna)
        >>> seq *= 2
        >>> seq
        MutableSeq('ATGATG', DNAAlphabet())
        """
        if not isinstance(other, int):
            raise TypeError("can't multiply {} by non-int type".format(self.__class__.__name__))
        return self.__class__(self.data * other, self.alphabet)

    def append(self, c):
        """Add a subsequence to the mutable sequence object.

        >>> my_seq = MutableSeq('ACTCGACGTCG')
        >>> my_seq.append('A')
        >>> my_seq
        MutableSeq('ACTCGACGTCGA')

        No return value.
        """
        self.data.append(c)

    def insert(self, i, c):
        """Add a subsequence to the mutable sequence object at a given index.

        >>> my_seq = MutableSeq('ACTCGACGTCG')
        >>> my_seq.insert(0,'A')
        >>> my_seq
        MutableSeq('AACTCGACGTCG')
        >>> my_seq.insert(8,'G')
        >>> my_seq
        MutableSeq('AACTCGACGGTCG')

        No return value.
        """
        self.data.insert(i, c)

    def pop(self, i=(-1)):
        """Remove a subsequence of a single letter at given index.

        >>> my_seq = MutableSeq('ACTCGACGTCG')
        >>> my_seq.pop()
        'G'
        >>> my_seq
        MutableSeq('ACTCGACGTC')
        >>> my_seq.pop()
        'C'
        >>> my_seq
        MutableSeq('ACTCGACGT')

        Returns the last character of the sequence
        """
        c = self.data[i]
        del self.data[i]
        return c

    def remove(self, item):
        """Remove a subsequence of a single letter from mutable sequence.

        >>> my_seq = MutableSeq('ACTCGACGTCG')
        >>> my_seq.remove('C')
        >>> my_seq
        MutableSeq('ATCGACGTCG')
        >>> my_seq.remove('A')
        >>> my_seq
        MutableSeq('TCGACGTCG')

        No return value.
        """
        for i in range(len(self.data)):
            if self.data[i] == item:
                del self.data[i]
                return
        raise ValueError("MutableSeq.remove(x): x not in list")

    def count(self, sub, start=0, end=sys.maxsize):
        """Return a non-overlapping count, like that of a python string.

        This behaves like the python string method of the same name,
        which does a non-overlapping count!

        For an overlapping search use the newer count_overlap() method.

        Returns an integer, the number of occurrences of substring
        argument sub in the (sub)sequence given by [start:end].
        Optional arguments start and end are interpreted as in slice
        notation.

        Arguments:
         - sub - a string or another Seq object to look for
         - start - optional integer, slice start
         - end - optional integer, slice end

        e.g.

        >>> from Bio.Seq import MutableSeq
        >>> my_mseq = MutableSeq("AAAATGA")
        >>> print(my_mseq.count("A"))
        5
        >>> print(my_mseq.count("ATG"))
        1
        >>> print(my_mseq.count(Seq("AT")))
        1
        >>> print(my_mseq.count("AT", 2, -1))
        1

        HOWEVER, please note because that python strings, Seq objects and
        MutableSeq objects do a non-overlapping search, this may not give
        the answer you expect:

        >>> "AAAA".count("AA")
        2
        >>> print(MutableSeq("AAAA").count("AA"))
        2

        An overlapping search would give the answer as three!
        """
        try:
            # TODO - Should we check the alphabet?
            search = str(sub)
        except AttributeError:
            search = sub

        if not isinstance(search, basestring):
            raise TypeError("expected a string, Seq or MutableSeq")

        if len(search) == 1:
            # Try and be efficient and work directly from the array.
            count = 0
            for c in self.data[start:end]:
                if c == search:
                    count += 1
            return count
        else:
            # TODO - Can we do this more efficiently?
            return str(self).count(search, start, end)

    def count_overlap(self, sub, start=0, end=sys.maxsize):
        """Return an overlapping count.

        For a non-overlapping search use the count() method.

        Returns an integer, the number of occurrences of substring
        argument sub in the (sub)sequence given by [start:end].
        Optional arguments start and end are interpreted as in slice
        notation.

        Arguments:
         - sub - a string or another Seq object to look for
         - start - optional integer, slice start
         - end - optional integer, slice end

        e.g.

        >>> from Bio.Seq import MutableSeq
        >>> print(MutableSeq("AAAA").count_overlap("AA"))
        3
        >>> print(MutableSeq("ATATATATA").count_overlap("ATA"))
        4
        >>> print(MutableSeq("ATATATATA").count_overlap("ATA", 3, -1))
        1

        Where substrings do not overlap, should behave the same as
        the count() method:

        >>> from Bio.Seq import MutableSeq
        >>> my_mseq = MutableSeq("AAAATGA")
        >>> print(my_mseq.count_overlap("A"))
        5
        >>> my_mseq.count_overlap("A") == my_mseq.count("A")
        True
        >>> print(my_mseq.count_overlap("ATG"))
        1
        >>> my_mseq.count_overlap("ATG") == my_mseq.count("ATG")
        True
        >>> print(my_mseq.count_overlap(Seq("AT")))
        1
        >>> my_mseq.count_overlap(Seq("AT")) == my_mseq.count(Seq("AT"))
        True
        >>> print(my_mseq.count_overlap("AT", 2, -1))
        1
        >>> my_mseq.count_overlap("AT", 2, -1) == my_mseq.count("AT", 2, -1)
        True

        HOWEVER, do not use this method for such cases because the
        count() method is much for efficient.
        """
        # The implementation is currently identical to that of
        # Seq.count_overlap() apart from the definition of sub_str
        sub_str = str(sub)
        self_str = str(self)
        overlap_count = 0
        while True:
            start = self_str.find(sub_str, start, end) + 1
            if start != 0:
                overlap_count += 1
            else:
                return overlap_count

    def index(self, item):
        """Return first occurrence position of a single entry (i.e. letter).

        >>> my_seq = MutableSeq('ACTCGACGTCG')
        >>> my_seq.index('A')
        0
        >>> my_seq.index('T')
        2

        Note unlike a Biopython Seq object, or Python string, multi-letter
        subsequences are not supported.
        """
        for i in range(len(self.data)):
            if self.data[i] == item:
                return i
        raise ValueError("MutableSeq.index(x): x not in list")

    def reverse(self):
        """Modify the mutable sequence to reverse itself.

        No return value.
        """
        self.data.reverse()

    def complement(self):
        """Modify the mutable sequence to take on its complement.

        Trying to complement a protein sequence raises an exception.

        No return value.
        """
        if isinstance(Alphabet._get_base_alphabet(self.alphabet),
                      Alphabet.ProteinAlphabet):
            raise ValueError("Proteins do not have complements!")
        if self.alphabet in (IUPAC.ambiguous_dna, IUPAC.unambiguous_dna):
            d = ambiguous_dna_complement
        elif self.alphabet in (IUPAC.ambiguous_rna, IUPAC.unambiguous_rna):
            d = ambiguous_rna_complement
        elif 'U' in self.data and 'T' in self.data:
            # TODO - Handle this cleanly?
            raise ValueError("Mixed RNA/DNA found")
        elif 'U' in self.data:
            d = ambiguous_rna_complement
        else:
            d = ambiguous_dna_complement
        mixed = d.copy()  # We're going to edit this to be mixed case!
        mixed.update((x.lower(), y.lower()) for x, y in d.items())
        self.data = [mixed[_] for _ in self.data]
        self.data = array.array(self.array_indicator, self.data)

    def reverse_complement(self):
        """Modify the mutable sequence to take on its reverse complement.

        Trying to reverse complement a protein sequence raises an exception.

        No return value.
        """
        self.complement()
        self.data.reverse()

    def extend(self, other):
        """Add a sequence to the original mutable sequence object.

        >>> my_seq = MutableSeq('ACTCGACGTCG')
        >>> my_seq.extend('A')
        >>> my_seq
        MutableSeq('ACTCGACGTCGA')
        >>> my_seq.extend('TTT')
        >>> my_seq
        MutableSeq('ACTCGACGTCGATTT')

        No return value.
        """
        if isinstance(other, MutableSeq):
            for c in other.data:
                self.data.append(c)
        else:
            for c in other:
                self.data.append(c)

    def toseq(self):
        """Return the full sequence as a new immutable Seq object.

        >>> from Bio.Seq import Seq
        >>> from Bio.Alphabet import IUPAC
        >>> my_mseq = MutableSeq("MKQHKAMIVALIVICITAVVAAL",
        ...                      IUPAC.protein)
        >>> my_mseq
        MutableSeq('MKQHKAMIVALIVICITAVVAAL', IUPACProtein())
        >>> my_mseq.toseq()
        Seq('MKQHKAMIVALIVICITAVVAAL', IUPACProtein())

        Note that the alphabet is preserved.
        """
        return Seq("".join(self.data), self.alphabet)


# The transcribe, backward_transcribe, and translate functions are
# user-friendly versions of the corresponding functions in Bio.Transcribe
# and Bio.Translate. The functions work both on Seq objects, and on strings.

def transcribe(dna):
    """Transcribe a DNA sequence into RNA.

    If given a string, returns a new string object.

    Given a Seq or MutableSeq, returns a new Seq object with an RNA alphabet.

    Trying to transcribe a protein or RNA sequence raises an exception.

    e.g.

    >>> transcribe("ACTGN")
    'ACUGN'
    """
    if isinstance(dna, Seq):
        return dna.transcribe()
    elif isinstance(dna, MutableSeq):
        return dna.toseq().transcribe()
    else:
        return dna.replace('T', 'U').replace('t', 'u')


def back_transcribe(rna):
    """Return the RNA sequence back-transcribed into DNA.

    If given a string, returns a new string object.

    Given a Seq or MutableSeq, returns a new Seq object with an RNA alphabet.

    Trying to transcribe a protein or DNA sequence raises an exception.

    e.g.

    >>> back_transcribe("ACUGN")
    'ACTGN'
    """
    if isinstance(rna, Seq):
        return rna.back_transcribe()
    elif isinstance(rna, MutableSeq):
        return rna.toseq().back_transcribe()
    else:
        return rna.replace('U', 'T').replace('u', 't')


def _translate_str(sequence, table, stop_symbol="*", to_stop=False,
                   cds=False, pos_stop="X", gap=None):
    """Translate nucleotide string into a protein string (PRIVATE).

    Arguments:
     - sequence - a string
     - table - a CodonTable object (NOT a table name or id number)
     - stop_symbol - a single character string, what to use for terminators.
     - to_stop - boolean, should translation terminate at the first
       in frame stop codon?  If there is no in-frame stop codon
       then translation continues to the end.
     - pos_stop - a single character string for a possible stop codon
       (e.g. TAN or NNN)
     - cds - Boolean, indicates this is a complete CDS.  If True, this
       checks the sequence starts with a valid alternative start
       codon (which will be translated as methionine, M), that the
       sequence length is a multiple of three, and that there is a
       single in frame stop codon at the end (this will be excluded
       from the protein sequence, regardless of the to_stop option).
       If these tests fail, an exception is raised.
     - gap - Single character string to denote symbol used for gaps.
       Defaults to None.

    Returns a string.

    e.g.

    >>> from Bio.Data import CodonTable
    >>> table = CodonTable.ambiguous_dna_by_id[1]
    >>> _translate_str("AAA", table)
    'K'
    >>> _translate_str("TAR", table)
    '*'
    >>> _translate_str("TAN", table)
    'X'
    >>> _translate_str("TAN", table, pos_stop="@")
    '@'
    >>> _translate_str("TA?", table)
    Traceback (most recent call last):
       ...
    Bio.Data.CodonTable.TranslationError: Codon 'TA?' is invalid

    In a change to older versions of Biopython, partial codons are now
    always regarded as an error (previously only checked if cds=True)
    and will trigger a warning (likely to become an exception in a
    future release).

    If **cds=True**, the start and stop codons are checked, and the start
    codon will be translated at methionine. The sequence must be an
    while number of codons.

    >>> _translate_str("ATGCCCTAG", table, cds=True)
    'MP'
    >>> _translate_str("AAACCCTAG", table, cds=True)
    Traceback (most recent call last):
       ...
    Bio.Data.CodonTable.TranslationError: First codon 'AAA' is not a start codon
    >>> _translate_str("ATGCCCTAGCCCTAG", table, cds=True)
    Traceback (most recent call last):
       ...
    Bio.Data.CodonTable.TranslationError: Extra in frame stop codon found.
    """
    sequence = sequence.upper()
    amino_acids = []
    forward_table = table.forward_table
    stop_codons = table.stop_codons
    if table.nucleotide_alphabet.letters is not None:
        valid_letters = set(table.nucleotide_alphabet.letters.upper())
    else:
        # Assume the worst case, ambiguous DNA or RNA:
        valid_letters = set(_ambiguous_dna_letters.upper() +
                            _ambiguous_rna_letters.upper())
    n = len(sequence)

    # Check for tables with 'ambiguous' (dual-coding) stop codons:
    dual_coding = [c for c in stop_codons if c in forward_table]
    if dual_coding:
        c = dual_coding[0]
        if to_stop:
            raise ValueError("You cannot use 'to_stop=True' with this table "
                             "as it contains {} codon(s) which can be both "
                             " STOP and an  amino acid (e.g. '{}' -> '{}' or "
                             "STOP)."
                             .format(len(dual_coding), c, forward_table[c]))
        warnings.warn("This table contains {} codon(s) which code(s) for both "
                      "STOP and an amino acid (e.g. '{}' -> '{}' or STOP). "
                      "Such codons will be translated as amino acid."
                      .format(len(dual_coding), c, forward_table[c]),
                      BiopythonWarning)

    if cds:
        if str(sequence[:3]).upper() not in table.start_codons:
            raise CodonTable.TranslationError(
                "First codon '{0}' is not a start codon".format(sequence[:3]))
        if n % 3 != 0:
            raise CodonTable.TranslationError(
                "Sequence length {0} is not a multiple of three".format(n))
        if str(sequence[-3:]).upper() not in stop_codons:
            raise CodonTable.TranslationError(
                "Final codon '{0}' is not a stop codon".format(sequence[-3:]))
        # Don't translate the stop symbol, and manually translate the M
        sequence = sequence[3:-3]
        n -= 6
        amino_acids = ["M"]
    elif n % 3 != 0:
        warnings.warn("Partial codon, len(sequence) not a multiple of three. "
                      "Explicitly trim the sequence or add trailing N before "
                      "translation. This may become an error in future.",
                      BiopythonWarning)
    if gap is not None:
        if not isinstance(gap, basestring):
            raise TypeError("Gap character should be a single character "
                            "string.")
        elif len(gap) > 1:
            raise ValueError("Gap character should be a single character "
                             "string.")

    for i in range(0, n - n % 3, 3):
        codon = sequence[i:i + 3]
        try:
            amino_acids.append(forward_table[codon])
        except (KeyError, CodonTable.TranslationError):
            if codon in table.stop_codons:
                if cds:
                    raise CodonTable.TranslationError(
                        "Extra in frame stop codon found.")
                if to_stop:
                    break
                amino_acids.append(stop_symbol)
            elif valid_letters.issuperset(set(codon)):
                # Possible stop codon (e.g. NNN or TAN)
                amino_acids.append(pos_stop)
            elif gap is not None and codon == gap * 3:
                # Gapped translation
                amino_acids.append(gap)
            else:
                raise CodonTable.TranslationError(
                    "Codon '{0}' is invalid".format(codon))
    return "".join(amino_acids)


def translate(sequence, table="Standard", stop_symbol="*", to_stop=False,
              cds=False, gap=None):
    """Translate a nucleotide sequence into amino acids.

    If given a string, returns a new string object. Given a Seq or
    MutableSeq, returns a Seq object with a protein alphabet.

    Arguments:
     - table - Which codon table to use?  This can be either a name
       (string), an NCBI identifier (integer), or a CodonTable object
       (useful for non-standard genetic codes).  Defaults to the "Standard"
       table.
     - stop_symbol - Single character string, what to use for any
       terminators, defaults to the asterisk, "*".
     - to_stop - Boolean, defaults to False meaning do a full
       translation continuing on past any stop codons
       (translated as the specified stop_symbol).  If
       True, translation is terminated at the first in
       frame stop codon (and the stop_symbol is not
       appended to the returned protein sequence).
     - cds - Boolean, indicates this is a complete CDS.  If True, this
       checks the sequence starts with a valid alternative start
       codon (which will be translated as methionine, M), that the
       sequence length is a multiple of three, and that there is a
       single in frame stop codon at the end (this will be excluded
       from the protein sequence, regardless of the to_stop option).
       If these tests fail, an exception is raised.
     - gap - Single character string to denote symbol used for gaps.
       Defaults to None.

    A simple string example using the default (standard) genetic code:

    >>> coding_dna = "GTGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG"
    >>> translate(coding_dna)
    'VAIVMGR*KGAR*'
    >>> translate(coding_dna, stop_symbol="@")
    'VAIVMGR@KGAR@'
    >>> translate(coding_dna, to_stop=True)
    'VAIVMGR'

    Now using NCBI table 2, where TGA is not a stop codon:

    >>> translate(coding_dna, table=2)
    'VAIVMGRWKGAR*'
    >>> translate(coding_dna, table=2, to_stop=True)
    'VAIVMGRWKGAR'

    In fact this example uses an alternative start codon valid under NCBI
    table 2, GTG, which means this example is a complete valid CDS which
    when translated should really start with methionine (not valine):

    >>> translate(coding_dna, table=2, cds=True)
    'MAIVMGRWKGAR'

    Note that if the sequence has no in-frame stop codon, then the to_stop
    argument has no effect:

    >>> coding_dna2 = "GTGGCCATTGTAATGGGCCGC"
    >>> translate(coding_dna2)
    'VAIVMGR'
    >>> translate(coding_dna2, to_stop=True)
    'VAIVMGR'

    NOTE - Ambiguous codons like "TAN" or "NNN" could be an amino acid
    or a stop codon.  These are translated as "X".  Any invalid codon
    (e.g. "TA?" or "T-A") will throw a TranslationError.

    It will however translate either DNA or RNA.

    NOTE - Since version 1.71 Biopython contains codon tables with 'ambiguous
    stop codons'. These are stop codons with unambiguous sequence but which
    have a context dependent coding as STOP or as amino acid. With these tables
    'to_stop' must be False (otherwise a ValueError is raised). The dual
    coding codons will always be translated as amino acid, except for
    'cds=True', where the last codon will be translated as STOP.

    >>> coding_dna3 = "ATGGCACGGAAGTGA"
    >>> translate(coding_dna3)
    'MARK*'

    >>> translate(coding_dna3, table=27)  # Table 27: TGA -> STOP or W
    'MARKW'

    It will however raise a BiopythonWarning (not shown).

    >>> translate(coding_dna3, table=27, cds=True)
    'MARK'

    >>> translate(coding_dna3, table=27, to_stop=True)
    Traceback (most recent call last):
       ...
    ValueError: You cannot use 'to_stop=True' with this table ...
    """
    if isinstance(sequence, Seq):
        return sequence.translate(table, stop_symbol, to_stop, cds)
    elif isinstance(sequence, MutableSeq):
        # Return a Seq object
        return sequence.toseq().translate(table, stop_symbol, to_stop, cds)
    else:
        # Assume its a string, return a string
        try:
            codon_table = CodonTable.ambiguous_generic_by_id[int(table)]
        except ValueError:
            codon_table = CodonTable.ambiguous_generic_by_name[table]
        except (AttributeError, TypeError):
            if isinstance(table, CodonTable.CodonTable):
                codon_table = table
            else:
                raise ValueError('Bad table argument')
        return _translate_str(sequence, codon_table, stop_symbol, to_stop, cds,
                              gap=gap)


def reverse_complement(sequence):
    """Return the reverse complement sequence of a nucleotide string.

    If given a string, returns a new string object.
    Given a Seq or a MutableSeq, returns a new Seq object with the same
    alphabet.

    Supports unambiguous and ambiguous nucleotide sequences.

    e.g.

    >>> reverse_complement("ACTG-NH")
    'DN-CAGT'
    """
    return complement(sequence)[::-1]


def complement(sequence):
    """Return the complement sequence of a nucleotide string.

    If given a string, returns a new string object.
    Given a Seq or a MutableSeq, returns a new Seq object with the same
    alphabet.

    Supports unambiguous and ambiguous nucleotide sequences.

    e.g.

    >>> complement("ACTG-NH")
    'TGAC-ND'
    """
    if isinstance(sequence, Seq):
        # Return a Seq
        return sequence.complement()
    elif isinstance(sequence, MutableSeq):
        # Return a Seq
        # Don't use the MutableSeq reverse_complement method as it is
        # 'in place'.
        return sequence.toseq().complement()

    # Assume its a string.
    # In order to avoid some code duplication, the old code would turn the
    # string into a Seq, use the reverse_complement method, and convert back
    # to a string.
    # This worked, but is over five times slower on short sequences!
    if ('U' in sequence or 'u' in sequence) \
            and ('T' in sequence or 't' in sequence):
        raise ValueError("Mixed RNA/DNA found")
    elif 'U' in sequence or 'u' in sequence:
        ttable = _rna_complement_table
    else:
        ttable = _dna_complement_table
    return sequence.translate(ttable)


def _test():
    """Run the Bio.Seq module's doctests (PRIVATE)."""
    print("Running doctests...")
    import doctest
    doctest.testmod(optionflags=doctest.IGNORE_EXCEPTION_DETAIL)
    print("Done")


if __name__ == "__main__":
    _test()