-2

If given the string "John Doe;Lodging;123;050617", which is a line within a file, I need to remove everything before and including the first semicolon, and after and including the last one. How can I do that without removing my ability to later split the remaining substring?

Previous questions do not address removing the portions once separated while retaining the portion needed for further use.

  • What do you want the string to look like? That would help make this question more clear. What final results do you want? – Garry Polley Jul 26 '17 at 20:51
  • The same answers apply there. Just split and then join what you want. – cs95 Jul 26 '17 at 20:59
  • I need Lodging;123 (Which will change because these are inputs from a .txt file). I then need to split the remaining substring and add each half to a list of categories and values, respectively. – Tayen Madsen Jul 26 '17 at 21:02

8 Answers8

2

Stepwise for clarity:

string = "John Doe;Lodging;123;050617"
lst = string.split(';')
lst = lst[1:-1]
string = ';'.join(lst)
print(string)
>>> 'Lodging;123'

As one line:

';'.join('John Doe;Lodging;123;050617'.split(';')[1:-1])
>>> 'Lodging;123'
Jason Stein
  • 714
  • 3
  • 10
2
test = "John Doe;Lodging;123;050617"
';'.join(test.split(';')[1:-1])
Zoidberg
  • 425
  • 3
  • 10
2
s = "John Doe;Lodging;123;050617"
new_s = ';'.join(s.split(';')[1:-1])

This will make new_s = 'Lodging;123'

jacoblaw
  • 1,263
  • 9
  • 9
0

The find method will give you the index of the first instance of a character in a string

original_s="John Doe;Lodging;123;050617"
idx = original_s.find(';')
new_s = original_s[i+1:]
print(new_s)
mdornfe1
  • 1,982
  • 1
  • 24
  • 42
0

Use str.partition and str.rpartition.

s = "John Doe;Lodging;123;050617"
s.partition(';')[-1].rpartition(';')[0] # Lodging;123

In terms of efficiency, this is probably the best solution. However, I find the split/join method more readable.

Jared Goguen
  • 8,772
  • 2
  • 18
  • 36
0

There are a few methods you could try. The simplest one is to split the string and reassemble it:

data = 'John Doe;Lodging;123;050617'
';'.join(data.split(';')[1:-1])

You could also use find and rfind (like find, but from the end of the string backwards:

data[data.find(';')+1:data.rfind(';')]

There's also partition and rpartition:

first, sep, remainder = data.partition(';')
middle, sep, final = remainder.rpartition(';')
Simon Fraser
  • 2,758
  • 18
  • 25
0

Try:

s = "John Doe;Lodging;123;050617"
print(';'.join(s.split(';')[1:-1]))
Md. Rezwanul Haque
  • 2,882
  • 7
  • 28
  • 45
-1

Try this: use str.find() function to locate the first occurance of ';' and then substring from that point to the end using [:]

aStr = "John Doe;Lodging;123;050617"
aStr = aStr[aStr.find(';')+1:]
print(aStr)
Lodging;123;050617
nanojohn
  • 572
  • 1
  • 3
  • 13