In [ ]:
my_string = 'Python is my favorite programming language!'
In [ ]:
my_string
In [ ]:
type(my_string)
In [ ]:
len(my_string)

Respecting PEP8 with long strings

In [ ]:
long_story = ('Lorem ipsum dolor sit amet, consectetur adipiscing elit.' 
              'Pellentesque eget tincidunt felis. Ut ac vestibulum est.' 
              'In sed ipsum sit amet sapien scelerisque bibendum. Sed ' 
              'sagittis purus eu diam fermentum pellentesque.')
long_story

str.replace()

If you don't know how it works, you can always check the help:

In [ ]:
help(str.replace)

This will not modify my_string because replace is not done in-place.

In [ ]:
my_string.replace('a', '?')
print(my_string)

You have to store the return value of replace instead.

In [ ]:
my_modified_string = my_string.replace('is', 'will be')
print(my_modified_string)

str.format()

In [ ]:
secret = '{} is cool'.format('Python')
print(secret)
In [ ]:
print('My name is {} {}, you can call me {}.'.format('John', 'Doe', 'John'))
# is the same as:
print('My name is {first} {family}, you can call me {first}.'.format(first='John', family='Doe'))

str.join()

In [ ]:
pandas = 'pandas'
numpy = 'numpy'
requests = 'requests'
cool_python_libs = ', '.join([pandas, numpy, requests])
In [ ]:
print('Some cool python libraries: {}'.format(cool_python_libs))

Alternatives (not as Pythonic and slower):

In [ ]:
cool_python_libs = pandas + ', ' + numpy + ', ' + requests
print('Some cool python libraries: {}'.format(cool_python_libs))

cool_python_libs = pandas
cool_python_libs += ', ' + numpy
cool_python_libs += ', ' + requests
print('Some cool python libraries: {}'.format(cool_python_libs))

str.upper(), str.lower(), str.title()

In [ ]:
mixed_case = 'PyTHoN hackER'
In [ ]:
mixed_case.upper()
In [ ]:
mixed_case.lower()
In [ ]:
mixed_case.title()

str.strip()

In [ ]:
ugly_formatted = ' \n \t Some story to tell '
stripped = ugly_formatted.strip()

print('ugly: {}'.format(ugly_formatted))
print('stripped: {}'.format(ugly_formatted.strip()))

str.split()

In [ ]:
sentence = 'three different words'
words = sentence.split()
print(words)
In [ ]:
type(words)
In [ ]:
secret_binary_data = '01001,101101,11100000'
binaries = secret_binary_data.split(',')
print(binaries)

Calling multiple methods in a row

In [ ]:
ugly_mixed_case = '   ThIS LooKs BAd '
pretty = ugly_mixed_case.strip().lower().replace('bad', 'good')
print(pretty)

Note that execution order is from left to right. Thus, this won't work:

In [ ]:
pretty = ugly_mixed_case.replace('bad', 'good').strip().lower()
print(pretty)
In [ ]:
two_lines = 'First line\nSecond line'
print(two_lines)
In [ ]:
indented = '\tThis will be indented'
print(indented)