1

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

tdelaney
  • 73,364
  • 6
  • 83
  • 116
Blank Reaver
  • 225
  • 3
  • 5
  • 17

3 Answers3

3

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'.

jeremysprofile
  • 10,028
  • 4
  • 33
  • 53
3

The camelize function will receive the string string and will split it in strings of consecutive alphanumeric characters

split('([^a-zA-Z0-9])', "example name") # => ['example', ' ', 'name']

Each string of the split result will be capitalized

[a.capitalize() for a in ['example', ' ', 'name']] # => ['Example', ' ', 'Name']

And will be filtered with isalnum() condition which checks the string contains only alphanumeric characters (Deleting the space element of the array)

[a.capitalize() for a in ['example', ' ', 'name'] if a.isalnum()] # => ['Example', 'Name']

Then will be joined using the separator '' (Empty string).

''.join(a.capitalize() for a in ['example', ' ', 'name'] if a.isalnum()) # => 'ExampleName'
0

Input to function is string.

isalnum() :The method isalnum() checks whether the string consists of alphanumeric characters.

.join() : Python String join() ,The join() is a string method which returns a string concatenated with the elements of an iterable

capitalize(): It returns a copy of the string with only its first character capitalized.

split() :The method split() returns a list of all the words in the string.

Understanding above will return your output for given input string

Roshan Bagdiya
  • 2,048
  • 21
  • 41