Results 1 to 5 of 5

Thread: python strings

  1. #1
    Join Date
    Jan 2006
    Location
    Netherlands
    Beans
    513
    Distro
    The Feisty Fawn Testing

    python strings

    Hi,
    I'm creating a program that can help me learn my Greek words.
    But I need to divide a string in two parts.

    To make it more clear, I have this string:
    Code:
    "koeien = cows"
    And I want to divide it in:
    Code:
    "koeien"
    and
    "cows"
    What is the easiest way to do this?
    The only way I can think of is making a list from the string. Indexing the location of the "=". And then doing something like:

    Code:
    part1 = list[:indexed_location-1]
    part2 = list[indexed_location+2:]
    There must be an easier way...
    Thanks in advance!
    Huh?

  2. #2
    Join Date
    Dec 2006
    Beans
    37

    Re: python strings

    Hi!

    Well, I think the easiest way would be to use split():
    Code:
    In [1]: s = "koeien = cows"
    
    In [2]: s.split("=")
    Out[2]: ['koeien ', ' cows']
    Regards, mawe

  3. #3
    Join Date
    Jan 2006
    Location
    @ ~/
    Beans
    1,694

    Re: python strings

    An then if you need to remove any white space before or after you could do something like:
    Code:
    s = "koeien = cows"
    news = s.split("=")
    news1 = news[0]
    news2 = news[1]
    news1 = news1.rstrip()
    news2 = news2.strip()
    Not the most elegant code i've ever written...
    Using ubuntu offline?
    Want to install new programs?
    Check out wubdepends
    If Stupidity got us into this mess,
    then why can’t it get us out?

  4. #4
    Join Date
    Dec 2006
    Beans
    37

    Re: python strings

    Ah, the whitespace, sorry, I forgot about that
    Code:
    s.split(" = ")
    or (that's how I would do it)
    Code:
    [elem.strip() for elem in s.split("=")]
    Regards, mawe

  5. #5
    Join Date
    Jan 2006
    Location
    Netherlands
    Beans
    513
    Distro
    The Feisty Fawn Testing

    Re: python strings

    OK. Thanks a lot!
    Huh?

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •