简体   繁体   中英

How to identify ordered substrings in string using python?

I am new to python, so my question would be naive but I would appreciate your suggestion that help me get to the solution of it.

For example I have string "aeshfytifghkjgiomntrop" and I want to find ordered substrings from it. How should I approach?

Scan the string using enumerate to issue index and value. Print string parts when chars are decreasing and start a new substring:

s = "aeshfytifghkjgiomntrop"

prev_c = None
prev_i = 0

for i,c in enumerate(s):
    if prev_c>c:
        print(s[prev_i:i])
        prev_i=i
    prev_c=c
print(s[prev_i:])

result:

aes
h
fy
t
i
fghk
j
gio
mnt
r
op

(No particular Python magic here, could be done simply even with C)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM