Python Frequently Asked Questions, Release 3.9.5 19 2.3. Numbers and strings (continues on next page) You can’t, because strings are immutable. In most situations, you should simply construct a new string from the various parts you want to assemble it from. However, if you need an object with the ability to modify in-place unicode data, try using an$_{io.StringIO}$ object or the$_{array}$ module: To convert, e.g., the number 144 to the string ‘144’, use the built-in type constructor$_{str()}$ . If you want a hexadec- imal or octal representation, use the built-in functions$_{hex()}$ or$_{oct()}$ . For fancy formatting, see the f-strings and formatstrings sections, e.g.$_{"{:04d}".format(144)}$ yields$_{'0144'}$ yields$_{'0.333'}$ . eval() also has the effect of interpreting numbers as Python expressions, so that e.g.$_{eval('09')}$ gives a syntax error because Python does not allow leading ‘0’ in a decimal number (except ‘0’). Do not use the built-in function$_{eval()}$ if all you need is to convert strings to numbers.$_{eval()}$ will be significantly slower and it presents a security risk: someone could pass you a Python expression that might have unwanted side effects. For example, someone could pass$_{__import__('os').system("rm -rf $HOME")}$ which would erase your home directory. By default, these interpret the number as decimal, so that int('0144') == 144 holds true, and int('0x144') raises$_{ValueError}$.$_{int(string, base)}$ takes the base to convert from as a second op- tional argument, so int( '0x144', 16) == 324 . If the base is specified as 0, the number is interpreted using Python’s rules: a leading ‘0o’ indicates octal, and ‘0x’ indicates a hex number. For integers, use the built-in$_{int()}$ type constructor, e.g.$_{int('144') == 144}$ . Similarly,$_{float()}$ converts to floating-point, e.g.$_{float('144') == 144.0}$ . There are few real use cases for$_{i % j}$when$_{j}$ is negative. When$_{j}$ is positive, there are many, and in virtually all of them it’s more useful for$_{i % j}$to be$_{>= 0}$ . If the clock says 10 now, what did it say 200 hours ago?$_{-190 %}$ 12 == 2 is useful; -190 % 12 == -10 is a bug waiting to bite. then integer division has to return the floor. C also requires that identity to hold, and then compilers that truncate$_{i}$ // j need to make$_{i % j}$have the same sign as$_{i}$ . It’s primarily driven by the desire that$_{i % j}$have the same sign as$_{j}$. If you want that, and also want: 2.3.2 Why does -22 // 10 return -3? 2.3.3 How do I convert a string to a number? 2.3.4 How do I convert a number to a string? 2.3.5 How do I modify a string in place? >>> import io >>> s ="Hello, world " >>> sio =io.StringIO(s) >>> sio.getvalue() 'Hello, world' >>> sio.seek(7) 7 >>> sio.write("there!") 6 >>> sio.getvalue() 'Hello, there!' >>> import array >>> a =array.array('u', s) i ==(i //j)*j +(i %j)