I would like to split M22 (so split the string M and the number 22)
I tried finding help from the internet, but most solutions are too complicated too begin with.
CodePudding user response:
If it's always : 1 letter 2 digit, just slice the string
v = "M22"
letter, digits = v[0], v[1:]
print(letter, digits) # M 22
If the amount of each is variable, use a regex
import re
v = "M22"
letter, digits = re.search("([A-Z] )(\d )", v).groups()
print(letter, digits) # M 22
CodePudding user response:
To split the string "M22" into the string "M" and the number 22, you can use the split() method and a regular expression.
Here is an example of how you can do this in JavaScript:
const str = "M22"
const [string, number] = str.split(/([0-9] )/)
console.log(string) // Output: "M"
console.log(number) // Output: "22"
In the code above, the split() method is called on the str string and passed a regular expression that matches one or more digits. This regular expression is used to split the string into two parts: the part before the digits and the part with the digits.
The two parts of the string are then destructured from the resulting array and assigned to the string and number variables. The string variable will contain the string "M" and the number variable will contain the number 22.
I hope this helps! Let me know if you have any other questions.
CodePudding user response:
[delete, misunderstood some things]