w3resource

Python: Convert a given string to Snake case

Python String: Exercise-97 with Solution

From Wikipedia,
Snake case (stylized as snake_case) refers to the style of writing in which each space is replaced by an underscore (_) character, and the first letter of each word written in lowercase. It is a commonly used naming convention in computing, for example for variable and subroutine names, and for filenames. One study has found that readers can recognize snake case values more quickly than camel case.

Write a Python program to convert a given string to Snake case.

  • Use re.sub() to match all words in the string, str.lower() to lowercase them.
  • Use re.sub() to replace any - characters with spaces.
  • Finally, use str.join() to combine all words using - as the separator.

Sample Solution:

Python Code:

from re import sub
def snake_case(s):
  return '_'.join(
    sub('([A-Z][a-z]+)', r' \1',
    sub('([A-Z]+)', r' \1',
    s.replace('-', ' '))).split()).lower()

print(snake_case('JavaScript'))
print(snake_case('Foo-Bar'))
print(snake_case('foo_bar'))
print(snake_case('--foo.bar'))
print(snake_case('Foo-BAR'))
print(snake_case('fooBAR'))
print(snake_case('foo bar'))

Sample Output:

java_script
foo_bar
foo_bar
foo.bar
foo_bar
foo_bar
foo_bar

Flowchart:

Flowchart: Convert a given string to snake case.

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to convert a given string to camelcase.
Next: Write a Python program to decapitalize the first letter of a given string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

Python: Tips of the Day

Returns the symmetric difference between two iterables, without filtering out duplicate values:

Example:

def tips_symmetric_difference(p, q):
  _p, _q = set(p), set(q)
  return [item for item in p if item not in _q] + [item for item in q if item not in _p]
print(tips_symmetric_difference([2, 4, 6], [2, 4, 8]))

Output:

[6, 8]

 





We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook