如何使用整数和字符串将字符串输入转换为元组

时间:2015-04-08 06:13:17

标签: python string python-2.7

我正在尝试编写一个提供字符串并将其转换为元组的函数。例如,给定这一行:

'1/2/3/some text and 5/4=3'

我希望输出为:

(1, 2, 3, 'some text and 5/4=3')

我知道我可以使用split函数,但我对如何对它进行切片感到困惑,因此从“some text”开始的文本被计为字符串而不是分开。

任何帮助将不胜感激!

3 个答案:

答案 0 :(得分:3)

您可以使用maxsplit参数限制拆分量:

  

str.split([sep[, maxsplit]])
  使用 sep 作为分隔符字符串,返回字符串中单词的列表。如果给出 maxsplit ,则最多 maxsplit 分割完成。

您需要3次拆分:

>>> line = '1/2/3/some text and 5/4=3'
>>> values = line.split('/', 3)
>>> values
['1', '2', '3', 'some text and 5/4=3']

要获得整数,我会将类型列表映射到值:

>>> types = [int, int, int, str]
>>> [type(value) for type, value in zip(types, values)]
[1, 2, 3, 'some text and 5/4=3']

如果不能处理该行,那将是因为尝试将字符串转换为整数失败。它也可能产生少于4个值的列表。

您可以将其包装在try/except块中:

def parse(line):
    values = line.split('/', 3)
    if len(values) < 4:
        return None
    else:
        types = [int, int, int, str]
        try:
            return tuple(type(value) for type, value in zip(types, values))
        except ValueError:
            return None

使用中:

>>> parse('1/2/3/some text and 5/4=3')
(1, 2, 3, 'some text and 5/4=3')

>>> None is parse('12/a/412/3/4/Here is some random text, like 5/4=3')
True

答案 1 :(得分:1)

您可以使用regular expression之类的:

import re
string = '1/2/3/some text and 5/4=3'
match = re.search(r'(\d*/){3}[A-z,\s]+', string)

if match is not None and match.start() == 0:
     nums = tuple(int(num) for num in string[:match.end()].split('/')[:-1])
     rest = string[string[:match.end()].rfind('/') + 1:]
     result = nums + (rest,)
else:
     result = None

给出:

(1, 2, 3, 'some text and 5/4=3')

如果string = '1/4/5/2/3/ some text and 5/4=3'给出:

None

答案 2 :(得分:0)

try:
    result = tuple(int(part) if i < 3 else part for i, part in enumerate(text.split('/', 3)))
    if len(result) < 3:
        result = None
except ValueError:
    result = None

text.split('/', 3)分裂斜线,但最多3次,即最多4次。

int(part) if i < 3尝试将前3个项解析为整数。如果其中任何一个看起来不是整数,则会引发ValueError,这将导致结果为None

相关问题