Skip to main content

Posts

Showing posts with the label string

Python - StringIO - Treat Text Like File

🐍 At times we need a file to run a code. Python allows you to treat a text/string like a file for that purpose. It is not really a file, but it lets you treat it that way. You need a module called StringIO for it. Use Jupyter Notebooks to run the following code. StringIO Let's begin by importing StringIO import io Next, we create a string and store it in a variable. message = 'This is just a normal string.' Let's apply StringIO magic to it and make it look like a file. f = io.StringIO(message) Now, we can do all file operations on it. Like read f.read() Output: 'This is just a normal string.' Like Write f.write(' Second line written to file like object') Output: 40 Like moving cursor to a location in the file f.seek(0) Output: 0 Like read again f.read() Output: 'This is just a normal string. Second line written to file like object' Like closing the file f.close() After closing 'f' cannot carry out the file functions.

Python - .strip(), .capitalize(), .title(), .spit()

🐍 .strip() removes certain characters from both ends of the string. .capitalize() capitalizes the first letter of the string and sets the rest of the string to lower case. .title() capitalizes first letter of every word in the string. Example Run the following code in Jupyter notebook and you will see how each of the above functions work. a = "   john SNOW   " b = "0000CAEsy0james00" print(a.strip().capitalize()+" loves "+b.strip('0').title()) .strip() .strip() removes all spaces from the front and back of a string. Not the spaces in between. .strip() has default argument as space, i.e. ' '. But if you pass another character, it will look for that character in front and back of the string and remove it. For example, if you run print('0000James0Cameron000'.strip('0')) , it will remove all 0s from front and back and print ' James0Cameron '. Note that the 0 in between remains as it is. You can pass a string too. Exa...

Python - Convert Decimal Number to Binary

🐍  Using Python, create a converter that converts decimal base number into binary base number. Solution def convertDecimalToBinary(decinum):          binum = ''     rem = decinum          while rem>0:         binum = binum + str(rem%2)         rem = rem//2          return binum[::-1] if __name__=='__main__':          decinum = int(input("Enter a decimal number: "))     print(f'The binary equivalent of {decinum} is {convertDecimalToBinary(decinum)}')