Skip to content

Camel to snake case conversion doesn't add an underscore after a digit #140

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Matt343 opened this issue Sep 22, 2021 · 3 comments
Closed
Assignees
Labels
enhancement Enhancement request good first issue Good for newcomers

Comments

@Matt343
Copy link

Matt343 commented Sep 22, 2021

The pyutils.camel_to_snake function does not add an underscore if a capital letter occurs after a non-letter character. For example, came_to_snake("python2Thing") returns python2thing instead of python2_thing. This seems counterintuitive, as it changes the case of the T without adding an underscore as usual.

@Cito
Copy link
Member

Cito commented Sep 22, 2021

Thanks for reporting. I agree, python2_thing would be the expected conversion. It's also what I get when I convert it with PyCharm or Visual Studio Code.

The pyutils function currently uses the same method as python-string-utils, which has this "bug". I'll see if I can find a better way when I find some spare time. If you know any better method, please let me know.

@Cito Cito self-assigned this Sep 22, 2021
@Cito Cito added enhancement Enhancement request good first issue Good for newcomers labels Sep 22, 2021
@Cito Cito changed the title Came to snake doesn't add an underscore after a digit Camel to snake case conversion doesn't add an underscore after a digit Sep 22, 2021
@gosella
Copy link

gosella commented Sep 28, 2021

In the past, I used this conversion function with great success:

>>> import re

>>> CAMEL_CASE_TO_SNAKE_CASE_RE = re.compile('((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))')

>>> def camel_to_snake(a_string):
...     return CAMEL_CASE_TO_SNAKE_CASE_RE.sub(r'_\1', a_string).lower()

>>> camel_to_snake('python2Thing')
'python2_thing'

Credits to https://stackoverflow.com/a/12867228 (last given example)

@Cito
Copy link
Member

Cito commented Sep 29, 2021

Thanks @gosella. I solved it in a similar way by making the minimal necessary change to the existing regex so that the "python2Thing" works as expecetd. If there are edge cases where your regex works better let me know, we can always add more tests and improve.

@Cito Cito closed this as completed Sep 29, 2021
Cito added a commit that referenced this issue Sep 29, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement Enhancement request good first issue Good for newcomers
Projects
None yet
Development

No branches or pull requests

3 participants