0

For example, is it possible to convert the input

x = 10hr

into something like

y = 10
z = hr

I considering slicing, but the individual parts of the string will never be of a fixed length -- for example, the base string could also be something like 365d or 9minutes.

I'm aware of split() and re.match which can separate items into a list/group based on delimitation. But I'm curious what the shortest way to split a string containing a string and an integer into two separate variables is, without having to reassign the elements of the list.

3
  • 1
    "But I'm curious what the shortest way to split a string containing a string and an integer into two separate variables is, without having to reassign the elements of the list." - do you have any reason to expect something shorter than y, z = whatever_you_have_in_mind_that_gives_a_list(x)? (Did you just not know you can do y, z = some_2_element_list?) Commented Mar 17, 2021 at 15:42
  • "I considering slicing, but the individual parts of the string will never be of a fixed length" This indicates that you need to calculate the length of the "number" part of your string. Commented Mar 17, 2021 at 15:49
  • 1
    Also, split() uses a delimiter, but re.match() doesn't have to. Rather, you tell it what part of the string to match with a regular expression and it returns that part. Commented Mar 17, 2021 at 15:49

2 Answers 2

3

You could use list comprehension and join it as a string

x='10hr'
digits="".join([i for i in x if not i.isalpha()])
letters="".join([i for i in x if i.isalpha()])
Sign up to request clarification or add additional context in comments.

Comments

1

You don't need some fancy function or regex for your use case

 x = '10hr'
 i=0
 while x[i].isdigit():
     i+=1

The solution assumes that the string is going to be in format you have mentioned: 10hr, 365d, 9minutes, etc.. Above loop will get you the first index value i for the string part

>>i
2
>>x[:i]
'10'
>>x[i:]
'hr'

1 Comment

@martineau Thanks for letting me know about the indentation.. I did not notice it when I posted it

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.