Samuel Grande
Samuel Grande

Reputation: 21

Erase characters from a string until a specific character

Python 3.4

I've got an Excel file with some messy organizing, but one this is for sure:

I need EVERYTHING except the stuff that appears before the very first comma in every single line, the comma included.

Example:

Print command of the file gives me this:

Word1 Funky,Left Side,UDLRDURLUDRUDLUR

Nothing (because not) exists lol extraline,Right Side,RBRGBRGBRGRBGRBGBR

What I want to get is this:

Left Side,UDLRDURLUDRUDLUR

Right Side,RBRGBRGBRGRBGRBGBR

I'd also like to make that into a dictionary:

dictionary = {"Left Side":"UDLRDURLUDRUDLUR", "Right Side":"RBRGBRGBRGRBGRBGBR",}

So basically I want to get rid of everything until the first comma (comma included), make the second part the key (ends at second comma), and third part the value (line ends with value).

What would be the easiest way to execute this?

Upvotes: 0

Views: 32

Answers (1)

David Hammen
David Hammen

Reputation: 33126

Suppose s contains the string to be examined:

s = "word1,Left Side,UDLRDURLUDRUDLUR"

There are a number of ways to get rid of everything up to and including the first comma. You can use

  • Slicing coupled with find: s[s.find(',')+1:]
    This expression will yield the desired result if the string s contain at least one comma, but it will yield the entire string if the string does not contain any commas.
  • Split coupled with indexing: s.split(',',1)[1]
    This expression will yield the desired result if the string s contain at least one comma, but it will raise IndexError if the string does not contain any commas.
  • Regular expressions, but that's overkill here.
  • Other techniques, but those are also overkill here.

Upvotes: 1

Related Questions