2

I have the following bit of code:

def test():
    fragment = ''
    fragment = raw_input('Enter input')
    while fragment not in string.ascii_letters:
        fragment = raw_input('Invalid character entered, try again: ')
    fragment.upper()
    print fragment*3

However when I run it, say for an input value of p, fragment gets printed as 'ppp' - all lower case, i.e. the fragment.upper() line does not run. The same thing happens if I replace that line with string.upper(fragment) (and adding import string at the beginning). Can someone tell me what I'm doing wrong?

tshepang
  • 12,111
  • 21
  • 91
  • 136
hotdogning
  • 43
  • 1
  • 1
  • 3
  • 1
    Does this answer your question? [Why doesn't calling a Python string method do anything unless you assign its output?](https://stackoverflow.com/questions/9189172/why-doesnt-calling-a-python-string-method-do-anything-unless-you-assign-its-out) – KetZoomer Apr 23 '21 at 22:26

3 Answers3

16

Strings are immutable. So functions like str.upper() will not modify str but return a new string.

>>> name = "xyz"
>>> name.upper()
'XYZ'
>>> print name
xyz  # Notice that it's still in lower case.
>>> name_upper = name.upper()
>>> print name_upper
XYZ

So instead of fragment.upper() in your code, you need to do new_variable = fragment.upper()and then use this new_variable.

varunl
  • 19,499
  • 5
  • 29
  • 47
7

You're not realizing that strings in Python are immutable and that string methods and operations return new strings.

>>> print 'ppp'.upper()
PPP
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • #this. u have to do something like fragment == fragment.upper() had the same problem with a filter using .replace... it took my very long till i understood this. now i wont forget it again :D –  Feb 27 '12 at 09:53
3

String is a immutable object, so when you call

string.upper()

python would make a copy of the string, and when you come back call

print string

, it would be the original string, which is lower case. So when you need its upper case version, you have to say:

print string.upper()
7O'clock
  • 41
  • 9