How to correct the error? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How to correct the error? (/thread-486.html) |
How to correct the error? - Ponomarenko Pavlo - Oct-14-2016 z = '346 + 324 - 368' z.split('+', '-')
RE: How to correct the error? - snippsat - Oct-14-2016 split() don't work multiple delimiters. You can use re.spilt(). >>> import re >>> z = '346 + 324 - 368' >>> re.split(r'\W+', z) ['346', '324', '368'] >>> ' '.join(re.split(r'\W+', z)) '346 324 368'\W+ matches any non-word character (equal to [^a-zA-Z0-9_]) RE: How to correct the error? - Yoriz - Oct-14-2016 Adding to the previous answer and explaining the error. split can be passed two arguments,
If the string in question is always formatted as shown and you are only interested in getting the numbers without using re z = '346 + 324 - 368' z.split()[::2]
RE: How to correct the error? - metulburr - Oct-14-2016 a non regex method using string methods.... >>> z = '346 + 324 - 368' >>> x = z.maketrans('+-','..') >>> x {43: 46, 45: 46} >>> y = z.translate(x).split('.') >>> y ['346 ', ' 324 ', ' 368']of course at this point its a list and each string is not separate by one single space >>> a = list(map(str.strip, y)) >>> a ['346', '324', '368'] >>> ' '.join(a) '346 324 368'This would not matter of exact format as something like this z = '346 + 324 - 368 - 368 + 368 + 368 -45 -56- 368'would still split to this 346 324 368 368 368 368 45 56 368Using python3.x otherwise you have to import string and convert maketrans line to.... string.maketrans('+-','..') |