<jupyter_start><jupyter_text>Strings in Python  What is a string? A "string" is a series of characters of arbitrary length.Strings are immutable - they cannot be changed once created. When you modify a string, you automatically make a copy and modify the copy.<jupyter_code>s1 = 'Godzilla'
print s1, s1.upper(), s1<jupyter_output><empty_output><jupyter_text>String literals A "literal" is essentially a string constant, already spelled out for you. Python uses either on output, but that's just for formatting simplicity.<jupyter_code>"Godzilla"<jupyter_output><empty_output><jupyter_text>Single and double quotes Generally, a string literal can be in single ('), double ("), or triple (''') quotes. Single and double quotes are equivalent - use whichever you prefer (but be consistent). If you need to have a single or double quote in your literal, surround your literal with the other type, or use the backslash to escape the quote.<jupyter_code>"Godzilla's a kaiju."
'Godzilla\'s a kaiju.'
'We call him... "Godzilla".'<jupyter_output><empty_output><jupyter_text>Triple quotes (''') Triple quotes are a special form of quoting used for documenting your Python files (docstrings). We won't discuss that type here.  Raw strings Raw strings don't use any escape character interpretation. Use them when you have a complicated string that you don't want to clutter with lots of backslashes. Python puts them in for you.<jupyter_code>print('This is a\ncomplicated string with newline escapes in it.')
print(r'This is a\ncomplicated string with newline escapes in it.')<jupyter_output><empty_output><jupyter_text>Strings and numbers<jupyter_code>x=int('122', 3)
x+1<jupyter_output><empty_output><jupyter_text>String objects String objects are just the string variables you create in Python.<jupyter_code>kaiju = 'Godzilla'
print(kaiju)
kaiju<jupyter_output><empty_output><jupyter_text>Note the print() call shows no quotes, while the simple variable name did. That is a Python output convention. Just entering the name will call the repr() method, which displays the value of the argument as Python would see it when it reads it in, not as the user wants it.<jupyter_code>repr(kaiju)
print(repr(kaiju))<jupyter_output><empty_output><jupyter_text>String operators When you read text from a file, it's just that - text. No matter what the data represents, it's still text. To use it as a number, you have to explicitly convert it to a number.<jupyter_code>one = 1
two = '2'
print one, two, one + two
one = 1
two = int('2')
print one, two, one + two
num1 = 1.1
num2 = float('2.2')
print num1, num2, num1 + num2<jupyter_output><empty_output><jupyter_text>You can also do this with hexadecimal and octal numbers, or any other base, for that matter.<jupyter_code>print int('FF', 16)
print int('0xff', 16)
print int('777', 8)
print int('0777', 8)
print int('222', 7)
print int('110111001', 2)<jupyter_output><empty_output><jupyter_text>If the conversion cannot be done, an exception is thrown.<jupyter_code>print int('0xGG', 16)<jupyter_output><empty_output><jupyter_text>Concatenation<jupyter_code>kaiju1 = 'Godzilla'
kaiju2 = 'Mothra'
kaiju1 + ' versus ' + kaiju2<jupyter_output><empty_output><jupyter_text>Repetition<jupyter_code>'Run away! ' * 3<jupyter_output><empty_output><jupyter_text>String keywords  in() NOTE: This _particular_ statement is false regardless of how the statement is evaluated! :^)<jupyter_code>'Godzilla' in 'Godzilla vs Gamera'<jupyter_output><empty_output><jupyter_text>String functions  len()<jupyter_code>len(kaiju)<jupyter_output><empty_output><jupyter_text>String methods Remember - methods are functions attached to objects, accessed via the 'dot' notation.  Basic formatting and manipulation  capitalize()/lower()/upper()/swapcase()/title()<jupyter_code>kaiju.capitalize()
kaiju.lower()
kaiju.upper()
kaiju.swapcase()
'godzilla, king of the monsters'.title()<jupyter_output><empty_output><jupyter_text>center()/ljust()/rjust()<jupyter_code>kaiju.center(20, '*')
kaiju.ljust(20, '*')
kaiju.rjust(20, '*')<jupyter_output><empty_output><jupyter_text>expandtabs()<jupyter_code>tabbed_kaiju = '\tGodzilla'
print('[' + tabbed_kaiju + ']')
print('[' + tabbed_kaiju.expandtabs(16) + ']')<jupyter_output><empty_output><jupyter_text>join()<jupyter_code>' vs '.join(['Godzilla', 'Hedorah'])
','.join(['Godzilla', 'Mothra', 'King Ghidorah'])<jupyter_output><empty_output><jupyter_text>strip()/lstrip()/rstrip()<jupyter_code>'   Godzilla   '.strip()
'xxxGodzillayyy'.strip('xy')
'    Godzilla   '.lstrip()
'    Godzilla   '.rstrip()<jupyter_output><empty_output><jupyter_text>partition()/rpartition()<jupyter_code>battle = 'Godzilla x Gigan'
battle.partition(' x ')
battle = 'Godzilla and Jet Jaguar vs. Gigan and Megalon'
battle.partition(' vs. ')
battle = 'Godzilla vs Megalon vs Jet Jaguar'
battle.partition('vs')
battle = 'Godzilla vs Megalon vs Jet Jaguar'
battle.rpartition('vs')<jupyter_output><empty_output><jupyter_text>replace()<jupyter_code>battle = 'Godzilla vs Mothra'
battle.replace('Mothra', 'Anguiras')
battle = 'Godzilla vs a monster and another monster'
battle.replace('monster', 'kaiju', 2)
battle = 'Godzilla vs a monster and another monster and yet another monster'
battle.replace('monster', 'kaiju', 2)<jupyter_output><empty_output><jupyter_text>split()/rsplit()<jupyter_code>battle = 'Godzilla vs King Ghidorah vs Mothra'
battle.split(' vs ')
kaijus = 'Godzilla,Mothra,King Ghidorah'
kaijus.split(',')
kaijus = 'Godzilla Mothra King Ghidorah'
kaijus.split()
kaijus = 'Godzilla,Mothra,King Ghidorah,Megalon'
kaijus.rsplit(',', 2)<jupyter_output><empty_output><jupyter_text>splitlines()<jupyter_code>kaijus_in_lines = 'Godzilla\nMothra\nKing Ghidorah\nEbirah'
print(kaijus_in_lines)
kaijus_in_lines.splitlines()
kaijus_in_lines.splitlines(True)<jupyter_output><empty_output><jupyter_text>zfill()<jupyter_code>age_of_Godzilla = 60
age_string = str(age_of_Godzilla)
print(age_string, age_string.zfill(5))<jupyter_output><empty_output><jupyter_text>String information  isXXX()<jupyter_code>print('Godzilla'.isalnum())
print('*Godzilla*'.isalnum())
print('Godzilla123'.isalnum())
print('Godzilla'.isalpha())
print('Godzilla123'.isalpha())
print('Godzilla'.isdigit())
print('60'.isdigit())
print('SpaceGodzilla'.isspace())
print('   '.isspace())
print('Godzilla'.islower())
print('godzilla'.islower())
print('Godzilla'.isupper())
print('GODZILLA'.isupper())
print('Godzilla vs Mothra'.istitle())
print('Godzilla X Mothra'.istitle())<jupyter_output><empty_output><jupyter_text>count()<jupyter_code>monsters = 'Godzilla and Space Godzilla and MechaGodzilla'
print 'There are ', monsters.count('Godzilla'), ' Godzillas.'
print 'There are ', monsters.count('Godzilla', len('Godzilla')), ' pseudo-Godzillas.'<jupyter_output><empty_output><jupyter_text>startswith()/endswith()<jupyter_code>king_kaiju = 'Godzilla'
print king_kaiju.startswith('God')
print king_kaiju.endswith('lla')
print king_kaiju.startswith('G')
print king_kaiju.endswith('amera')<jupyter_output><empty_output><jupyter_text>find()/index()/rfind()/rindex()<jupyter_code>kaiju_string = 'Godzilla,Gamera,Gorgo,Space Godzilla'
print 'The first Godz is at position', kaiju_string.find('Godz')
print 'The second Godz is at position', kaiju_string.find('Godz', len('Godz'))
kaiju_string.index('Minilla')
kaiju_string.rindex('Godzilla')<jupyter_output><empty_output><jupyter_text>Advanced features  decode()/encode()/translate() Used to convert strings to/from Unicode and other systems. Rarely used in science code.  String formatting Similar to formatting in C, FORTRAN, etc.. There is a _lot_ more to this than I am showing here.<jupyter_code>kaiju = 'Godzilla'
age = 60
print '%s is %d years old.' % (kaiju, age)<jupyter_output><empty_output><jupyter_text>The _string_ module The _string_ module is the Python equivalent of "junk DNA" in living organisms. It's been around since the beginning, but many of its functions have been superseded by evolution. But some ancient code still relies on it, so they leave the old parts in....For modern code, the _string_ module does have some useful constants and functions.<jupyter_code>import string
print string.ascii_letters
print string.ascii_lowercase
print string.ascii_uppercase
print string.digits
print string.hexdigits
print string.octdigits
print string.letters
print string.lowercase
print string.uppercase
print string.printable
print string.punctuation
print string.whitespace<jupyter_output><empty_output><jupyter_text>The _string_ module also provides the _Formatter_ class, which can be useful for sophisticated text formatting.  Regular Expressions  What is a regular expression? Regular expressions ('regexps') are essentially a mini-language for describing string operations. Everything shown above with string methods and operators can be done with regular expressions. Most of the time, the regular expression verrsion is more concise. But not always more readable....To use regular expressions, you have to import the 're' module.<jupyter_code>import re<jupyter_output><empty_output><jupyter_text>A very short, whirlwind tour of regular expressions  Scanning<jupyter_code>kaiju_truth = 'Godzilla is the King of the Monsters. Ebirah is also a monster, but looks like a giant lobster.'
re.findall('Godz', kaiju_truth)
print re.findall('(^.+) is the King', kaiju_truth)<jupyter_output><empty_output><jupyter_text>For simple searches like this, using in() is typically easier.Regexps are by default case-sensitive.<jupyter_code>print re.findall('\. (.+) is also', kaiju_truth)
print re.findall('(.+) is also a (.+)', kaiju_truth)[0]
print re.findall('\. (.+) is also a (.+),', kaiju_truth)[0]<jupyter_output><empty_output><jupyter_text>Changing<jupyter_code>some_kaiju = 'Godzilla, Space Godzilla, Mechagodzilla'
print re.sub('Godzilla', 'Gamera', some_kaiju)
print re.sub('(?i)Godzilla', 'Gamera', some_kaiju)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12119372787051087, 'fraction_numerical': 0.008598887202832575, 'mean_word_length': 7.3708721422523285, 'pattern_counts': {'":': 0, '<': 137, '<?xml version=': 0, '>': 137, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '34', 'dir': 'jupyter-structured-clean-dedup', 'id': '755', 'license': 'MIT', 'n_tokens_mistral': 3467, 'n_tokens_neox': 3273, 'n_words': 907, 'path': 'Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb', 'repo_name': 'saudijack/unfpyboot', 'size': '9885'}