-2

How can I format this string in a list from :

('1496\n8584\n172\n5988\n7184\n704\n3448\n6580\n8504\n', '')

to :

('1496','8584','172','5988','7184','704','3448','6580','8504')

I think the way is to use re.sub() but I'm having trouble with the '\n' not escaping

Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
tommy45
  • 3
  • 1

5 Answers5

3

You do not need re.sub, str.split will suffice.

t = ('1496\n8584\n172\n5988\n7184\n704\n3448\n6580\n8504\n', '')

out = t[0].split()

# out : ['1496', '8584', '172', '5988', '7184', '704', '3448', '6580', '8504']

If you want it exactly in the format you provided, you can cast back to a tuple. Note that when you use (...) you are creating a tuple and not a list as you mentionned.

out = tuple(t[0].split())

# out : ('1496', '8584', '172', '5988', '7184', '704', '3448', '6580', '8504')
Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
  • why is `t` a tuple? it adds unnecessary complexity, just start with a string as in the question. – avigil Mar 07 '18 at 17:03
  • 1
    @avigil Because the question has been edited, I just did a rollback to preserve the initial intent which is to have a string inside a list/tuple. – Olivier Melançon Mar 07 '18 at 17:20
1

Hope this works-

a='1496\n8584\n172\n5988\n7184\n704\n3448\n6580\n8504\n'
b=a.split()
print(b)

Output-

['1496', '8584', '172', '5988', '7184', '704', '3448', '6580', '8504']

The a.split() splits the string by every occurrence of \n.

Abhisek Roy
  • 582
  • 12
  • 31
0

Instead of re.sub, use re.findall to grab every run of digits:

import re
s = ('1496\n8584\n172\n5988\n7184\n704\n3448\n6580\n8504\n', '')
new_s = tuple(i for b in map(lambda x:re.findall('\d+', x), filter(None, s)) for i in b)

Output:

('1496', '8584', '172', '5988', '7184', '704', '3448', '6580', '8504')
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
0

It's very simple. Use split function for strings.

#!/usr/bin/python
s = ('1496\n8584\n172\n5988\n7184\n704\n3448\n6580\n8504\n', '')
output=s[0].split()
print(output)

output you expected as list:

['1496', '8584', '172', '5988', '7184', '704', '3448', '6580', '8504']

If you want to get a tuple, use tuple function to convert.

#!/usr/bin/python
s = ('1496\n8584\n172\n5988\n7184\n704\n3448\n6580\n8504\n', '')
output=tuple(s[0].split())
print(output)

output as a tuple:

('1496', '8584', '172', '5988', '7184', '704', '3448', '6580', '8504')

Differences between tuple and list in python you can get here.

TigerTV.ru
  • 1,058
  • 2
  • 16
  • 34
0

This code resolved my problem

output = ('1496\n8584\n172\n5988\n7184\n704\n3448\n6580\n8504\n', '')
output = str(output)
output = re.sub('[^a-zA-Z0-9 .]|n','',output)
output = output.split()
print output
tommy45
  • 3
  • 1