Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separate string by characters in python

Tags:

python

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

like image 634
john terry Avatar asked Jul 13 '26 06:07

john terry


2 Answers

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']
like image 147
sheldonzy Avatar answered Jul 14 '26 21:07

sheldonzy


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']
like image 39
Austin Avatar answered Jul 14 '26 21:07

Austin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!