0

I have a string: "2y20w2d2h2m2s" I need to split it to be like that: ["2y","20w","2d","2h","2m"2s”] I tried to use re.split but i couldnt make it work this was my attempt: time = re.split("s m h d w y", time) *time is the string above finally, I will apricate of you would help understand how to make it work

2
  • 1
    Do the sections you want the string to split into always start with a 2? Commented May 3, 2020 at 15:02
  • a good Q that i forgot to sepcify but its not supposed to be only 2 its supposed to be any number Commented Jun 7, 2020 at 15:06

4 Answers 4

2

Code:

import re

time_str = "2y20w2d2h2m2s"
time = re.findall(r"(\d*\S)", time_str)
print(time)

Output:

>>> python3 test.py 
['2y', '20w', '2d', '2h', '2m', '2s']

Try it online:

Sign up to request clarification or add additional context in comments.

Comments

0

In case the sections you want the string to split into always start with 2, this does the trick:

string = "2y20w2d2h2m2s"

print(string.replace('2', ' 2').split())

Comments

0

Try:

import re

print(re.findall('(\d+[a-z])', "2y20w2d2h2m2s"))

Output

['2y', '20w', '2d', '2h', '2m', '2s']

Explanation

Regex pattern for 1 or more numbers followed by a letter

(\d+[a-z])

Comments

0

Being as specific as possible for your use case:

import re
s = "2y20w2d2h2m2s"
re.findall('([0-9]{1,2}[ywdhms]{1})', s)

Output: ['2y', '20w', '2d', '2h', '2m', '2s']

This produces exactly what you want with no extraneous letters or numbers with more than two digits.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.