简体   繁体   中英

Slice string till next char

Assume I have this kind of string Y18C9A8B88 and i want to get something like this

Y18C9A8B88.cut()
>>> [Y,18],[C,9],[A,8],[B,88]

I succeed doing that if the length of the num is equals to one but if its bigger it doesn't work

You can use regular expression for this:

import re
re.findall("(\w+?)(\d+)", "Y18C9A8B88")

Breakdown:

  • "\w+?" captures all strings up to the next digit and "\d+" capture all the digits (the ? ensure it does not capture letters that could be dealt with "\d" ).
  • The parenthesis tell it which part belong to which group.
  • re.findall makes sure that we try to match until the string is exhausted.

Assuming all the letters are capital and 1 letter is followed by n numbers then

import re
results = re.findall('[A-Z][0-9]*', "Y18C9A8B88")
results = [ [result[0], int(result[1:])] for result in results ]

Results is equal to:

[['Y', 18], ['C', 9], ['A', 8], ['B', 88]]

Just in the remote case scenario that you don't want to use regular expressions, you can try:

string = 'Y18C9A8B88'
letters = [ch for ch in string if ch.isalpha()]
nums = "".join([ch if ch.isdigit() else ' ' for ch in string]).strip().split()
result = [[*tuple_] for tuple_ in zip(letters, nums)]

Output:

[['Y', '18'], ['C', '9'], ['A', '8'], ['B', '88']]

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