Member Avatar for sravan953

I have a string, say for example:

str="aasd<script>"

How do I make Python to note down one character at a time until it encounters the '<'? I know it has to be a loop, but which function?

Thanks

Recommended Answers

All 4 Replies

First of all do not use 'str' as a variable name, it is a Python function.
Here is an example of the loop ...

mystr = "aasd<script>"

for c in mystr:
    if c == '<':
        break
    else:
        print(c)

>I know it has to be a loop, but which function?
Why are you so sure?

>>> s="asdf<script"
>>> print s[:s.find('<')]
asdf
>>>
Member Avatar for sravan953

>I know it has to be a loop, but which function?
Why are you so sure?

>>> s="asdf<script"
>>> print s[:s.find('<')]
asdf
>>>

I didn't understand, can you please explain to me your code character by character?

You should know that python supports slicing. If you do not, read the python tutorial.
The find function returns the first occurrence of the string you pass as the argument. [In the previous example, it returns 4].
So, when I say s[:find("<")] I mean to say " slice me s, from the beginning till the occurrence of '<' ".
You should perhaps go and read the manual if you still don't understand the code.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.