Python Strings
- use
""
or''
- for multiple lines use triple quotes
''' '''
- strings are iterable, i.e. can look up characters in the string by index
- can use negative indexes
- strings are immutable, must create a new string
- concatenate strings with
+
and multiple with*
- these will not automatically add spaces between strings
string.upper()
andstring.lower()
change the case of all the characters in the string to be upper or lowerstring.capitalize()
will just capitalize the first letter- create new string using using
.format()
- it looks for curly brackets and inserts the parameter
- example:
'William {}'.format('Faulkner')
creates the string 'William Faulkner' - example:
n1 = input('Enter a noun: ') v = input('Enter a verb: ') adj = input('Enter a adj: ') n2 = input('Enter a noun: ') r = '''The {} {} the {}{}'''.format(n1, v, adj, n2)
.split(delimiter)
will split into multiple strings at the delimiter- the delimiter is not in either string
.join()
lets you add new characters to a string- example:
result isfirst_three = 'abc' result = '+'.join(first_three)
a+b+c
- can also use with lists. example:
one_string iswords = ['The', 'fox', 'jumped', 'over', 'the', 'fence', '.'] one_string = ' '.join(words)
'The fox jumped over the fence .'
- example:
.strip()
strips leading and following white space from a string- can use
in
andnot in
keywords '\'
escape character\n
newline
- slicing:
name[start_index:end_index]
- start_index is included, end_index is not included
- works with strings and lists
- example:
gives usivan = 'In place of death there was light.' ivan[0:17]
'In place of death'
ivan[17:33]
gives us' there was light'
- example:
now list islist = ['a', 'b', 'c', 'd', 'e'] list[0:3]
['a', 'b', 'c']
- if start_index is 0 you can leave it empty
[:end_index]
- if end_index is last index in the iterable you can leave it empty
[start_index:]
- leaving both empty
[:]
returns the original iterable
.replace(param1, param2)
replaces every occurrence of one character with another- first param is the string to replace and the second param is the replacement string
- example:
equ is nowequ = 'All animals are equal.' equ = equ.replace('a', '@')
'All @nim@ls @re equ@l.'
string.index('character')
returns the first index the param string occurs at