-2

I'm just trying to understand how to make a value after value x (i.e. x+1) in a string be included in a split.

I've tried a for loop, of just for i: splitlist.append(i) and can end up printing [A, B, C, D, E].

samplestring = 'ABCDE'
for i in samplestring:
    splitlist = []
    if i+1 == (none):
        break
    else:
        splitlist.append(i,i+1)

I want to return ['AB', 'BC', 'CD', 'DE'] but instead end up with a type error in the line ;

if i+1 == (none):.

(TypeError: can only concatenate str (not "int") to str)

Charles
  • 324
  • 1
  • 13
  • 1
    As you iterate on `samplestring` in your for loop, `i` will take the value of each letter of samplestring, and you can't add 1 to a letter. – Thierry Lathuille Aug 12 '19 at 12:55
  • Loop over the length of the string minus one with an index, use that index to get the current (at the index) and the next (index plus one) character from the string. Append as single string to the list. – Some programmer dude Aug 12 '19 at 12:56
  • I think you can remove the whole thing with your `None`. i can't see why you would need it. Moreover, I think you mean `None` instead of `(none)` – Joseph Budin Aug 12 '19 at 12:57
  • Related: https://stackoverflow.com/q/6998245/1025391 and https://stackoverflow.com/q/6822725/1025391 – moooeeeep Aug 12 '19 at 13:00

4 Answers4

1

Use zip to group adjacent items together:

[f'{x}{y}' for x, y in zip(samplestring, samplestring[1:])]

Example:

samplestring = 'ABCDE'

print([f'{x}{y}' for x, y in zip(samplestring, samplestring[1:])])
# ['AB', 'BC', 'CD', 'DE']
Austin
  • 25,759
  • 4
  • 25
  • 48
1

There are a few problems:

  • you're creating an empty list every iteration
  • you're trying to combine a string: i with an integer: 1.
  • your way of checking if the string ended is a little weird, you know the length of the string (using len(samplestring)), so you can dictate how often you are to loop over it

To fix this you can use:

samplestring = 'ABCDEF'
splitlist = []
for i in range(len(samplestring) - 1):
    splitlist.append(samplestring[i] + samplestring[i+1])

This results in splitlist:

['AB', 'BC', 'CD', 'DE', 'EF']
Nathan
  • 3,558
  • 1
  • 18
  • 38
0
print([samplestring[i:i + 2] for i in len(samplestring) - 1])
Hank Chow
  • 446
  • 4
  • 13
0

Reason for Error - You are adding string and integer

sample = 'ABCDE'

print([sample[i]+sample[i+1] for i in range(0,len(sample)-1)])
Adi7
  • 51
  • 6