简体   繁体   中英

How to return variable names in camelCase given a string with phrases seperates by semi-colons?

How can I make each phrase in the string into camelCase and get rid of the colons? s = 'num things;perc rate;rate'

It should return ['numThings', 'percRate', 'rate']

Here is some sample code I am trying to work on:

def createVars(s):
    varlst = []
    varlst = s.split(';')
    try:
        for words in varlst:
            words.title()
            words.strip()
    except ValueError:
        print('String not entered')
    return varlst    

Note that neither title() nor strip() are in-place functions, so you'd need to assign them back. Furthermore, you'd need to somehow lowercase the first letter before returning a result.

You could probably do this in a single line, but here's an old fashioned approach (!) with a function and yield .

def foo(string):
    for x in string.split(';'):
        y = x.title().replace(' ', '')  
        yield y[0].lower() + y[1:]     # amazingly, this works for one length strings too

x = 'num things;perc rate;rate'

print(list(foo(x)))
['numThings', 'percRate', 'rate']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM