Strings
- Strings in Python can be enclosed by either double or single quotes.
- A string literal can span multiple lines, but there must be a backslash \ at the end of each line to escape the newline. String literals inside triple quotes, “”“” or ‘’‘, can multiple lines of text.
- Python strings are “immutable” which means they cannot be changed after they are created.(Any changes applied on strings should be assigned to a new string)
String methods
Python strings comes with an extensive number of methods. Here are some of the most common string methods:
- s.lower(), s.upper() – returns the lowercase or uppercase version of the string
- s.strip() – returns a string with whitespace removed from the start and end
- s.isalpha()/s.isdigit()/s.isspace()… – tests if all the string chars are in the various character classes
- s.startswith(‘other’), s.endswith(‘other’) – tests if the string starts or ends with the given other string
- s.find(‘other’) – searches for the given other string (not a regular expression) within s, and returns the first index where it begins or -1 if not found
String Slicing
- Characters in a string can be accessed using the standard [ ] syntax.
- Python allows very flexible slicing mechanism on strings.
s[1:4] is ‘ell’ – chars starting at index 1 and extending up to but not including index 4
s[1:] is ‘ello’ – omitting either index defaults to the start or end of the string
s[:] is ‘Hello’ – omitting both always gives us a copy of the whole thing (this is the pythonic way to copy a sequence like a string or list)
s[-1] is ‘o’ – last char (1st from the end)
s[:-3] is ‘He’ – going up to but not including the last 3 chars.
>>> file_path = "C:/windows/system32/meterpreter.exe"
>>>
>>> file_path[0]
'C'
>>> file_path[3:10]
'windows'
>>>
>>> file_path[-3:]
'exe'
>>> file_path.split('/')
['C:', 'windows', 'system32', 'meterpreter.exe']
>>>
String concatenation
- Python string concatenation is pretty straight forward.
- The ‘+’ does not automatically convert numbers or other types to string form. The str() function converts values to a string form so they can be combined with other strings.
>>> path = "/home/opt/"
>>> file = 'msfconsole'
>>>
>>> file_path = path+file
>>> file_path
'/home/opt/msfconsole'
>>> os.path.join('/home','opt','msfconsole')
'/home/opt/msfconsole'
>>> email = ['target', '@', 'example.com']
>>>
>>> a = ""
>>>
>>> a.join(email)
'target@example.com'
>>> "".join(email)
'target@example.com'