Jefe
Jefe

Reputation: 53

How to Loop through a string and return a new string that stops at a specific character

Getting back into Python after a 2 year hiatus. Don't remember the best way to loop through a string from the beginning and stopping at a certain character, then returning the string.

def my_string(long_string, char):

    newstr = " "
    for i in range(len(long_string)):
       if long_string[i] == char:
           # now what?

I know I need to create a new string, then start a loop to go through the existing string. But then I get stuck. I know I need to return the new string, but am not sure what the rest of my code should look like. Thanks in advance for your help.

Upvotes: 4

Views: 1130

Answers (6)

agtoever
agtoever

Reputation: 1699

I think split works better than index (returns error if character not found) or find (returns -1 if character isn't found).

>>> s,c='Who fwamed wodgew wabit?','w'
>>> s.split(c)[0]
'Who f'
>>> c='r'
>>> s.split(c)[0]
'Who fwamed wodgew wabit?' 

Explanation: split returns a list of the words in the string, using sep as the delimiter string. By returning the first item, this works exactly as specified.

Upvotes: 0

Mark Beilfuss
Mark Beilfuss

Reputation: 602

Use a string slice to grab the portion of the string you want. From your description it sounds like you want all characters up to the first occurrence of that character correct?

Try this for example. Tweak the indices to get the portion of the string you want.

long_string[0:i]

The answers that include the use of .index() will not work well if the target character doesn't exist in the string without catching the exception.

Upvotes: 1

ragardner
ragardner

Reputation: 1975

If the stop character is definitely in the string you can use .index() which will find the index of the first occurrence of the thing in brackets and slicing []

string = "hello op"
stopchar = " "

newstr = string[:string.index(stopchar)]

#newstr = "hello"

If you're not sure if the stop character is in the string you should use .find() which will not raise an error if it does not find the character:

newstr = string[:string.find(stopchar)]

If you don't want to stop at the first character and want to get all words before the stop character you could use this list comprehension:

string2 = "hello op today"
strings = [string2[:i] for i,c in enumerate(string2)
           if c == stopchar]
print (strings)

result:

['hello', 'hello op']

Upvotes: 0

akp
akp

Reputation: 637

try:
    print d[:d.index('y')]
except ValueError:
    print d

Upvotes: 1

JohEker
JohEker

Reputation: 627

You could create a list containing each char in the string and loop through the list.

mystr = raw_input("Input: ")
newStr = list(mystr)

print(newStr)

Then you can just loop through the list to meet your conditions

Upvotes: 0

If you just want to get the substring from the beginning of the long string until a certain char, you can just do the following:

>>> ch = 'r'
>>> s = 'Hello, world!'
>>> print(s[:s.find(ch)])
#  Hello, wo

Upvotes: 1

Related Questions