-2

Hey am new to python development and i am fully filled with a lots of doubts since am a newbie.Suppose

s = 'something'
for something in s:
   something = something + 1
   print  something

I know here something act as an index and it would print out the whole elements in s.

And in

s = 'something'
for something in s:
    s[something] = s[something] + 1
    print  something

I didnt understand the correct meaning of the second part of the code..Is it possible in python??.. '

Sorry for low grade question and any help would be appreciated ..

James Sapam
  • 16,036
  • 12
  • 50
  • 73

3 Answers3

3

When you loop through a string like this:

for c in 'something':
    print(c)

c does not act as an index, it acts as character of the string, so the output would be:

s
o
m
e
t
h
i
n
g

If you want to loop through the indices you can do:

s = 'something'
for i in range(len(s)):
    print(i)

And the output would be:

0
1
2
3
4
5
6
7
8

You can access a character from the string by indexing like this:

s = 'something'
for i in range(len(s)):
    print(s[i])

And the output of that would be:

s
o
m
e
t
h
i
n
g

If you want to loop through a string so that you get the characters as well as the indices, you can use the enumerate() function:

s = 'something'
for i, c in enumerate(s):
    print(i, c)

The output:

0 s
1 o
2 m
3 e
4 t
5 h
6 i
7 n
8 g

Note that strings are immutable, so you can't change them:

>>> s = 'something'
>>> s[0] = 'a'
TypeError: 'str' object does not support item assignment

When you do string concatenation, you are not actually changing the string, you are creating a new one.


EDIT 1

Strings have methods that can be called on them to do certain tasks, such as the .split() method:

>>> s = 'something'
>>> s.split('e')
['som', 'thing']

They also have some special methods like __getitem__. The following two are equivalent:

>>> s = 'something'
>>> s[0]
's'
>>> s.__getitem__(0)
's'

Other sequences like lists are mutable, so they also have a __setitem__ method:

>>> s = ['s', 'o', 'm', 'e', 't', 'h', 'i', 'n', 'g']
>>> s[0] = 't'
>>> s
['t', 'o', 'm', 'e', 't', 'h', 'i', 'n', 'g']
>>> s.__setitem__(0, 's')
>>> s
['s', 'o', 'm', 'e', 't', 'h', 'i', 'n', 'g']

EDIT 2

This is what happens when you try to do this s[something] = s[something] + 1:

>>> s = 'something'
>>> s[0] = s[0] + 1
TypeError: Can't convert 'int' object to str implicitly

The reason this happens is because s[0] is 's' so you are trying to add a number to a string, which doesn't make any sense. Then if you try and do s[something] = s[something] + 'a' you will get a TypeError because strings are immutable:

>>> s = 'something'
>>> s[0] = s[0] + 'a'
TypeError: 'str' object does not support item assignment

And this will definitely not work:

>>> s = 'something'
>>> s['a']
TypeError: string indices must be integers
Scorpion_God
  • 1,499
  • 10
  • 15
0

The square brackets after a variable name invoke __getitem__ or __setitem__ on the variable, depending on the context. So for example, x[i] = x[i] + 1 is equivalent to x.__setitem__(i, x.__getitem__(i) + 1). You can read up about this in the docs here:
https://docs.python.org/2/reference/datamodel.html

There are several built-in types that implement one or both of these, for example strings, tuples, lists, and dictionaries. For the sequence types (strings, tuples, lists) the "item" being accessed or set is an index, so for example print 'hello'[0] would print h because you are getting the character at the first index in the list.

In this case, it looks like the second piece of code would actually cause an error because strings are not mutable. This means that string objects can't be modified, so they won't have __setitem__ implemented and s[something] = s[something] + 1 would fail. This could work with a mutable type like list or dict though, for example:

s = [1, 1, 1]
s[0] = s[0] + 1
# s is now [2, 1, 1]
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
0

s[something] = s[something] + 1 shouldn't work; string values are immutable.

Syntax like s += "foo" actually creates a new string value from s + "foo", then assigns it to s, releasing the original value of s to be garbage collected.

A key thing to remember about all variables in Python is that they're just references to values. There's no guarantee the values aren't pooled somewhere and have a copy-on-write semantic. Another example is that a like like x = 5 doesn't set x to 5, it creates (or otherwise obtains) the value 5 and sets x to refer to it.

For the most part this distinction really doesn't matter. In general, the Right Thing(TM) happens.


The code:

s = 'something'
for something in s:
    # ... 

treats s like a list of characters and sets something to each one in sequence through the loop. (This is unlike JavaScript.) If you want the indices and not just the characters, use:

s = 'something'
for i, something in enumerate(s):
    # ... 

so s[something] = s[something] + 1 is not possible in any situations ..right ?

It works fine for lists (e.g. [1, 2, 3]) and dictionaries (e.g. {"a": 1, "b": 2}). Just not for strings.

If you simply want to get a string where every character is replaced with the next one, first split the string with a list comprehension:

l = [c for c in s]

Replace each character with the next one:

l2 = [chr(ord(c) + 1) for c in l]

and glue them back together into a new string:

s2 = ''.join(l2)

Putting it all together:

s = 'something'
s2 = ''.join([chr(ord(c) + 1) for c in s])
Mike DeSimone
  • 41,631
  • 10
  • 72
  • 96