0

I'm trying to write a function that will allow me to pass in a string and a character to split the string by.

This obviously works:

def delimit(inputValue, splitChar):
   splitValue = [x.strip() for x in inputValue.split(',')]
   print(splitValue)

delimit('100,    200,300   ,400,500',',')

Printing this:

['100', '200', '300', '400', '500']

But when I try to use a variable to specify the delimiting value, it doesn't work:

def delimit(inputValue, splitChar):
    splitChar = "'" + splitChar + "'"
    splitValue = [x.strip() for x in inputValue.split(splitChar)]
    print(splitValue)

delimit('100,    200,300   ,400,500',',')

Which returns:

['100, 200,300 ,400,500']

Is it possible to use a variable inside of split()? If so, how would I accomplish this?

3 Answers 3

1

Yes you can use a variable for your splitChar.
I think you are getting confused by other languages where single quotes denote char's while double quotes denote strings. In Python there is no difference between single quoted and double quoted strings. There also is no concept of a char type, only single character strings.

To make your function work you just need to remove your line splitChar = "'" + splitChar + "'" since this is making your splitChar string be ',' which is not what you want. splitChar is already storing the correct delimeter ,.

Sign up to request clarification or add additional context in comments.

Comments

0

Why did you add this line splitChar = "'" + splitChar + "'"? Now, the split char variable contains ',', which doesn't appear anywhere in your test string. Thus, split fails to split it as you wish.

Comments

0

If you take out splitChar = "'" + splitChar + "'" from your function, it will work. Concatenating "'" on either side of your split character will just add ' to each side of you split character string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.