'Need to make a list by splitting the given string in python
Input string has 'n' times of X. Like this "XXXXX"
Need to split the string and make out a list in which each character of the string(X) is each element of list.
Constraints:
0 <= X <= any number
'n' is unknown
Example 1: X is 12,
Input string : "121212121212121212"
Output list : [12,12,12,12,12,12,12,12,12]
Example 2: X is 2,
Input string : "2222"
Output list : [2,2,2,2]
Example 3: X is 489,
Input string : "489489489"
Output list : [489,489,489]
I tried this approach
my_list = list(input_string)
I am getting output like,
[1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2]
Can anyone help me to resolve this?
Edit 1: I am new to stackoverflow. Please help me to edit this question properly.
Edit 2: As this question is clear and understandable, please consider upvoting.
Solution 1:[1]
To decode this string you need 'n' and X anyway. Why not build it directly with:
li = [X] * n
Edit: If you don't have 'n', you could get it easily from the given string. (Under the condition that givenString only consist of X)
n = len(givenString) / len(str(X))
li = [X] * n
Solution 2:[2]
You can use regular expressions:
import re
x = input('Enter Your X : ')
mystr = input('Enter Your Input String : ')
result = re.findall(x, mystr)
print(result)
This outputs:
Enter Your X : 12
Enter Your Input String : 121212121212
['12', '12', '12', '12', '12', '12']
Solution 3:[3]
Here's a variant that makes sure the substrings all match the given pattern:
input_ = "121212121212121212"
x = "12"
res = []
while input_.startswith(x):
res.append(x)
input_ = input_[len(x):]
Solution 4:[4]
If X
is also unknown, you can use this:
import textwrap
def find_shortest_pattern(input_):
for len_ in range(1, int(len(input_) / 2) + 1):
patterns = textwrap.wrap(input_, len_)
if all(pattern == patterns[0] for pattern in patterns):
return patterns[0]
find_shortest_pattern("123123123")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Tomerikoo |
Solution 3 | |
Solution 4 | myke |