How to iterate over a string and return a new string that stops at a specific character

Return to Python after a two-year hiatus. Don't remember the best way to iterate over a string from the beginning and stop at a specific character and then return 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 line and then run a loop to go through the existing line. But then I got stuck. I know that I need to return a new line, but I'm not sure what the rest of my code looks like. Thanks in advance for your help.

+4
source share
6 answers

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

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

, . , , ?

, . , .

long_string[0:i]

, .index(), , .

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

, .index(), []

string = "hello op"
stopchar = " "

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

#newstr = "hello"

, , .find(), , :

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

, :

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

:

['hello', 'hello op']
0

, char, .

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

print(newStr)

.

0

, split , index ( , ) find ( -1, ).

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

: split , sep . , , .

0

Source: https://habr.com/ru/post/1684618/


All Articles