Please explain the below Python code to me. This answer works when submitted on CodeWars and I want help understanding the ins and outs of it. What is happening at each step of this program?
from re import split
def camelize(string):
return ''.join(a.capitalize() for a in split('([^a-zA-Z0-9])', string)
if a.isalnum())
Here is a test example:
camelize("example name") # => ExampleName
Sure! Regex stuff can be hard to just look at and understand at the start. First, let's break it down into the order things happen. Let's use the example input "test_of wORd editor"
First, we split the string into a list with split('([^a-zA-Z0-9])', string)
. This is split on every character that isn't a letter (uppercase or lowercase) or a number. This would convert our input into ['test', '_', 'of', ' ', 'wORd', ' ', 'editor']
.
Next, we are going to only keep part of our list by asking if each element in our list is alphanumeric with .isalnum()
. If not, we ignore that part of our list. If it is alpha-numeric, we call .capitalize()
on each element in the list, which converts the element to all lowercase with the exception of the first character, which is uppercase. This is a built-in python function that is doing the meat of what you want. These two parts together are done using list comprehension. I'm going to assume you know what that is. The output of this will be ['Test', 'Of', 'Word', 'Editor']
.
Lastly, we need to join the list together to be a string again. ''.join()
combines every element of the list together without spaces, returning 'TestOfWordEditor'
.