-12

Here how can i split the string into sub string like follows:

If my string is 'python' then it need to store like a1=py, a2=th, a3=on.

But the input will get by input() function. How can do it?

Rahul Agarwal
  • 4,034
  • 7
  • 27
  • 51
Naveen S
  • 31
  • 5
  • Are you trying to split every two characters? – blueseal Dec 31 '18 at 05:44
  • Yes. I am trying to split each two characters and that need to store in variable. Is it possible in for loop – Naveen S Dec 31 '18 at 05:46
  • 1
    Maybe you wanna check out the concept of slicing? – smitty_werbenjagermanjensen Dec 31 '18 at 05:47
  • Yeah, you can use a for loop. You can google the version you commented with :) You can't really google what you originally asked. – blueseal Dec 31 '18 at 05:47
  • 3
    Possible duplicate of [How do I reliably split a string in Python, when it may not contain the pattern, or all n elements?](https://stackoverflow.com/q/38149470/608639), [Split string with multiple delimiters in Python](https://stackoverflow.com/q/4998629/608639), [How to split a string into a list?](https://stackoverflow.com/q/743806/608639), [Is there a way to substring a string?](https://stackoverflow.com/q/663171/608639), etc. – jww Dec 31 '18 at 05:53

2 Answers2

1
s='python'
a1,a2,a3=[s[i:i+2] for i in range(0,len(s),2)]
print(a1,a2,a3)

Output

py th on

If you need to use input and variable split length

s=input('Enter String: ')
n=2
a1,a2,a3=[s[i:i+2] for i in range(0,len(s),n)]
print(a1,a2,a3)

Output

Enter String: python
py th on
Bitto
  • 7,937
  • 1
  • 16
  • 38
1

Try this one: If you want to get 2 length substring from given string.

In [114]: a
Out[114]: 'python'

In [115]: [a[i:i+2] for i in range(0, len(a), 2)]
Out[115]: ['py', 'th', 'on']

You can make 2 a variable, depending on which length substring you want.

Rohit-Pandey
  • 2,039
  • 17
  • 24