How to crop Python strings

Asked 2 years ago, Updated 2 years ago, 74 views

For example, a = QWASDFGHJK If there is a string like this, how do I print out ASDF and GHJK separately, excluding QW?

python string

2022-09-22 16:44

2 Answers

It depends on the case of separation, but if it's just a string separation, you can do it as follows.

Python String Related Materials

a = "QWASDFGHJK"

print a[2:6]

print a[6:len(a)]


2022-09-22 16:44

For your information, simply a[6:] will print it out from the 6th to the end. And even if a is 10 in length, if you write a[6:1000], the error does not occur and returns from the 6th to the end.

If you write it down as follows, it will be printed out by cutting off 4 pieces. At the end, even if there are 1 to 4 left, only the rest will be printed.

a = "QWASDFGHJK"
start = 2
finish = 6

while finish <= len(a):
    print a[start:finish]
    start += 4
    finish += 4


2022-09-22 16:44

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.