15 String Methods That Changed the Way I Work With Text in Python

What will you learn?

It is (almost) impossible not to work with strings and text in Python at some point. In this guide you will learn 15 ways of working with strings that will help you be more efficient.

Make sure to check the last ones, they are awesome and I use them all the time.

#1 replace()

This is one of my favorite. How often do you need to change a substring to another. This can be as simple as changing a character to another.

input_str = 'this is my slug'
slug = input_str.replace(' ', '_')

This will give ‘this_is_my_slug’ in slug.

#2 split()

You have a string and want to split it into words. This can be done with split()

input_str = 'this is my awesome string'
words = input_str.split()

Then words will contain the list [‘this’, ‘is’, ‘my’, ‘awesome’, ‘string’].

Notice you can set the separator as you wish, say to comma as follows: split(‘,’) then it will separate on comma.

#3 join()

Another favorite. You split something than you want to join it again, right?

input_str = 'this is my awesome string'
my_list = input_str.split()

output_str = '_'.join(my_list)

Then you have output_str to be ‘this_is_my_awesome_string’.

#4 in

In what?

Yes, you want to check if something is a substring of another.

input_str = 'this is my awesome string'

if 'awesome' in input_str:
    print('awesome')

if 'dull' in input_str:
    print('dll')

This will only print awesome.

#5 strip()

Often when you work with strings they will contain spaces in front and at the end as well as a new line.

input_str = '   I love this    '

output_str = input_str.strip()

This will give ‘I love this’ in output_str.

#6 isdigit()

Want to check if a string is a digit value?

input_str = '313'
if input_str.isdigit():
    print(f'{input_str} is digit')

input_str = '313a'
if input_str.isdigit():
    print(f'{input_str} is digit'

This will only be True for the top one.

Read this guide to learn some awesome f-strings (used above).

#7 Concatenate strings

This is such a great feature of Python. Yes, you can simply concatenate strings with a plus sign.

str_a = 'This is Cool'
str_b = ' and Amazing'
output_str = str_a + str_b

This output_str will be ‘This is Cool and Amazing’.

If you notice, this could be done with join as well.

output_str = ''.join((str_a, str_b))

This will give the same result.

#8 Formatted strings

Formatted strings are amazing and makes it easy to output variables. Formatted strings will output string representation of a variable between curly brackets. The formatted string starts with an f.

var_a = 27
var_b = 'Icecream'
print(f'Bought {var_a} items of {var_b}')

This will output ‘Bought 27 items of Icecream’.

#9 lower()

Want a string in lower case.

input_str = 'Hi My Best Friend'

print(input_str.lower())

This will give ‘hi my best friend’.

#10 startswith()

When processing strings, you might want to check if it starts with a specific part.

url = 'https://www.foobar.com/'

if url.startswith('https://'):
    print('HTTPS')

This will obviously print HTTPS for url.

#11 endswith()

Almost similar.

url = 'https://www.foobar.com/'

if url.endswith('/'):
    print('Slash')

It will print Slash. Not from Guns’n’Roses – no not him.

#12 count()

How many occurrences of a substring?

print('foo bar foobar barfoo'.count('foo'))

This will print 3.

#13 splitlines()

This one is amazing when you read a full text with new lines.

text = '''This is my text
and it is long
over multiple lines'''

lines = text.splitlines()

This will have lines [‘This is my text’, ‘and it is long’, ‘over multiple lines’].

#14 Check if string only contains certain characters

I use this all the time. You need to check if a string only contains specific characters. These characters are not standard or very specific to your use case.

Here is how you can solve it.

ef valid_characters(string: str):
    legal_characters = 'abcdefghijklmnopqrstuvwxyz0123456789._-'
    if set(string) <= set(legal_characters):
        return True
    else:
        return False

print(valid_characters('FooBar'))
print(valid_characters('foobar'))
print(valid_characters('foo_bar'))

This will print False, True, True.

#15 Replace and remove last item in itemized string

Am I the only one, which uses this all the time?

It could be comma separated string, and you need to remove the last one of them.

def convert(string: str):
    return ','.join(string.split(',')[:-1])

print(convert('this,is,my,test,remove_me'))

This will print ‘this_is_my_test’.

Want to learn more?

If this is something you like and you want to get started with Python, then check my 8 hours FREE video course with full explanations, projects on each levels, and guided solutions.

The course is structured with the following resources to improve your learning experience.

  • 17 video lessons teaching you everything you need to know to get started with Python.
  • 34 Jupyter Notebooks with lesson code and projects.
  • A FREE 70+ pages eBook with all the learnings from the lessons.

Leave a Reply Cancel reply

Exit mobile version