JoshJohnson
JoshJohnson

Reputation: 113

String output is not normal

I've faced a problem regarding string formatting in Python.

I have a certain problem to solve: the program accepts any string. Then it creates a list with elements as each character of the string. However, it should change elements that are == 's' to the character before them and after. Also, the character before the main one should be output two times.

Input: test_Stringss

Output: ['t', 'e', 'eet', 't', '_', '__t', 't', 'r', 'i', 'n', 'g', 'ggs', 's']

This is what I've came up with:

st = input("input string: ")
st = st.lower()
print(st)
l = []
for a in st:
  posA=st.find(a)
  print(posA)
  if (a=='s') and (posA!=len(st)) and (posA!=0):
    newst = st[posA-1 : posA]*2 + st[posA+1 : posA + 2]
    l.append(newst)
  else:
    l.append(a)
print(l)

However on the same input as shown in the example above it makes the following output: ['t', 'e', 'eet', 't', '_', 'eet', 't', 'r', 'i', 'n', 'g', 'eet', 'eet']

Been trying to deal with this problem for quite a while. I would really appreciate any help!

Upvotes: 0

Views: 50

Answers (3)

Shivam Jha
Shivam Jha

Reputation: 4482

Hope this is what you want, and not sure why there is an s in your Output, even if you want to replace s:

s = 'test_Strings'

for i,c in enumerate(s):
    if c.lower() != 's':
        print(c, end='')
    elif i == 0:
        print(s[1], end='')
    elif i == len(s) - 1:
        print(s[i-1]*2 , end='')
    else:
        print(s[i-1]*2 + s[i+1], end='')

# Output: teeett___ttringgg

Upvotes: 0

lucasdctr
lucasdctr

Reputation: 5

I think maybe the problem comes from the fact that the .find method only outputs the position of the first character of the string equals to the one you are searching for. Try using a while loop instead of the first for loop so that you have already the position of the variable you are searching for (it will be the incremented variable).

Upvotes: 0

Patrick Artner
Patrick Artner

Reputation: 51643

str.find(...) reports the first occurence of the letter in the string. Use enumerate instead - there is no need to search for the position inside the string:

st = "test_Stringss".lower() 
print(st)
l = []
for posA, a in enumerate(st):
    print(posA)
    if (a == 's') and (posA != len(st)) and (posA != 0):
        newst = st[posA-1 : posA]*2 + st[posA+1 : posA + 2]
        l.append(newst)
    else:
        l.append(a)
print(l) 

You need to fix the last character output though.

Upvotes: 1

Related Questions