Python:拆分字符串,按变量拆分

时间:2018-09-23 03:48:59

标签: python split

我正在尝试编写一个函数,该函数将允许我传递一个字符串和一个字符来分割字符串。

这显然可行:

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

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

打印此内容:

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

但是当我尝试使用变量指定分隔值时,它不起作用:

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

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

哪个返回:

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

是否可以在split()内使用变量?如果是这样,我该怎么做?

3 个答案:

答案 0 :(得分:1)

是的,您可以为splitChar使用变量。
我认为您对其他语言感到困惑,其中单引号表示char,而双引号表示字符串。在Python中,单引号和双引号字符串没有区别。也没有char类型的概念,只有单个字符串。

要使函数正常工作,只需要删除行splitChar = "'" + splitChar + "'",因为这会使splitChar字符串成为',',而这并不是您想要的。 splitChar已经存储了正确的分度符,

答案 1 :(得分:0)

您为什么添加此行splitChar = "'" + splitChar + "'"? 现在,split char变量包含',',它不会出现在测试字符串的任何地方。因此,split无法按您的意愿进行拆分。

答案 2 :(得分:0)

如果您从函数中取出splitChar = "'" + splitChar + "'",它将起作用。在分割字符的两边串联“'”只会在分割字符串的每一边加上'。