I'm trying to separate characters from any given strings and making subsring with it. For example,
str='abcd' => 'ab','bc','cd'
Here is my solution,
str='abcdef'
a=[]
for i in range(len(str)):
a.append(str[i:i+2])
a.remove(a[-1])
print(a)
This works but I would like to know better way to do it.
Thanks
A possible solution without external modules (like your implementation, but cleaner).
[my_str[i:i+2] for i in range(len(my_str) - 1)]
so
In [3]: my_str='abcdef'
In [4]: [my_str[i:i+2] for i in range(len(my_str) - 1)]
Out[4]: ['ab', 'bc', 'cd', 'de', 'ef']
Use zip() (Built-in):
[f'{x}{y}' for x, y in zip(s, s[1:])]
Code:
s = 'abcdef'
print([f'{x}{y}' for x, y in zip(s, s[1:])]) # Python 3.6+. For previous versions, use below line.
# [x + y for x, y in zip(s, s[1:])]
# Outputs: ['ab', 'bc', 'cd', 'de', 'ef']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With