Recently I have a made a function
in python which converts any string in camelCase
format, but while passing different types of string in this function I got into a problem when I tried to pass "BirdFlight"
it did not convert it into camelCase
.
NOTE - I used python built-in re
module.
import re
def camelCase(string):
string = re.sub(r'(_|-)+', ' ', string).title().replace(' ', '')
return ''.join([string[0].lower() + string[1:]])
After that I created a list
of 3 different types of string to pass in the function.
differentTypeOfString = ['bird flight', 'BirdFlight', '-BIRD-FLIGHT-']
for i in differentTypeOfString:
print(camelCase(i))
ignore the varialbe name I will change it after.
OUTPUT
#1 birdFlight
#2 birdflight
#3 birdFlight
Well there are more problems I encountered just now 😅. I increased the string types inside my list:
differentTypeOfString = ['bird flight', 'BirdFlight', '-BIRD-FLIGHT-', 'Bird-Flight', 'bird_flight', '--bird.flight', 'Bird-FLIGHT', 'birdFLIGHT']
Now I am getting this Output
#1 birdFlight
#2 birdflight
#3 birdFlight
#4 birdFlight
#5 birdFlight
#6 bird.Flight
#7 birdFlight
#8 birdflight
Same problem with "birdFLIGHT"
and in "--bird.flight"
the "." (dot) is not removing.
This works for your current examples. The re.sub
adds a space between any existing <lower><upper> sequence.
import re
def camelCase(string):
string = re.sub(r'(?:(?<=[a-z])(?=[A-Z]))|[^a-zA-Z]', ' ', string).title().replace(' ', '')
return ''.join([string[0].lower() + string[1:]])
differentTypeOfString = ['bird flight', 'BirdFlight', '-BIRD-FLIGHT-', 'Bird-Flight', 'bird_flight', '--bird.flight', 'Bird-FLIGHT', 'birdFLIGHT']
for i in differentTypeOfString:
print(camelCase(i))
Output:
birdFlight
birdFlight
birdFlight
birdFlight
birdFlight
birdFlight
birdFlight
birdFlight