One place for hosting & domains

      Strings

      How to Encode and Decode Strings with Base64 in JavaScript


      While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or
      edited it to ensure you have an error-free learning experience. It’s on our list, and we’re working on it!
      You can help us out by using the “report an issue” button at the bottom of the tutorial.

      Encoding and decoding a string in Base64 with JavaScript can be quite handy.

      For that we have the btoa() and atob() functions. These two base64 helper functions are a core part of the HTML spec and available in all modern browsers.

      • btoa() encodes to Base64
      • atob() decodes from Base64
      // Define the string
      var string = 'Hello World!';
      
      // Encode the String
      var encodedString = btoa(string);
      console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"
      
      // Decode the String
      var decodedString = atob(encodedString);
      console.log(decodedString); // Outputs: "Hello World!"
      

      Copy and paste the examples above in your Chrome Console to see them working.

      Common use cases for Base64

      • Packaging things like form input and JSON strings into a character set that’s safer to use in HTTP requests
      • Representing binary data in a way that’s compatible with HTML/JavaScript/CSS. – You can embed an image inline in a CSS or JavaScript file using Base64, for example.

      What Base64 is not:

      • It’s in no way meant to be a secure encryption method,
      • It’s not a compression method, encoding a string to Base64 typically results in ~33% longer output.



      Source link

      How To Use f-strings to Create Strings in Python 3


      The author selected the COVID-19 Relief Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      Python strings are variable length sequences of characters and symbols. Strings allow your program to manipulate and track text and also display that text to your users.

      Python includes several methods for building strings including the %-formatting style and the str.format() method. The str.format() method is newer than the %-formatting style and is detailed in How To Use String Formatters in Python 3. f-string formatting is the newest method of string formatting in Python and offers conveniences, such as using expressions within strings, which aren’t available in either the %-formatting style or the str.format() method.

      In this tutorial, you will learn how to use Python 3’s f-strings to create strings dynamically.

      Prerequisites

      To get the most out of this tutorial, it is recommended to have some familiarity with programming in Python 3. You can review these tutorials for the necessary background information:

      Using Variables in f-strings

      Programs commonly need to substitute a variable into a string. Python’s f-strings provide a convenient way for us to do this. Let’s consider an example:

      ocean_description = "deep blue"
      print(f"The ocean is {ocean_description} today")
      

      If we run this code, we’ll receive output like the following:

      Output

      The ocean is deep blue today

      First, we bind the string deep blue to a variable named ocean_description. On the next line, we activate f-string formatting by prefixing a string with f. f-strings interpret the expressions inside of {} characters as Python. So, by saying {ocean_description}, we are instructing Python to insert the value of the ocean_description variable into our string. The resulting string is then printed: The ocean is deep blue today.

      Using Arbitrary Expressions in f-strings

      In the previous section, we learned how to substitute a variable into an f-string. f-strings also allow the substitution of arbitrary Python expressions:

      print(f"1 + 1 = {1 + 1}")
      

      If we run this code, we’ll receive output like the following:

      Output

      1 + 1 = 2

      In this example, we again activate f-string formatting by including the f prefix on a string. Inside of the {} characters, we include a valid Python expression of 1 + 1. The end result of that expression is 2, which gets included in the final string that is printed.

      Just about any valid Python expression can be used in an f-string. In the next example, we’ll demonstrate accessing a dictionary value inside of an f-string:

      ocean_dict = {"shark": "fish"}
      print(f"A shark is a kind of {ocean_dict['shark']}")
      

      We’ll receive output like the following:

      Output

      A shark is a kind of fish

      On the first line we define a dictionary with a single key/value pair: the key shark is mapped to the value fish. On the next line, we embed the expression ocean_dict['shark'] inside of {} characters in an f-string. The result of that embedded expression is fish, which is included in the output.

      Including the repr of an Object

      By default, f-strings will coerce included Python objects to strings so that the objects can be made a part of the final string. By default, Python uses the __str__ method defined on objects to coerce them to strings. Built-in Python objects (for example: lists, dictionaries, integers, floats) include predefined __str__ methods so that the coercion process happens seamlessly.

      Sometimes it’s helpful to use an alternate representation of the object in the generated string. f-strings include a directive that allows the repr of a Python object to be included in the final output. The repr of a Python object is a debugging description of the given Python object.

      Let’s consider an example to make the distinction between __str__ and repr clearer. To call repr on the variable we add !r to the end of the expression:

      from datetime import datetime
      
      now = datetime.now()
      print(f"{now}")
      print(f"{now!r}")
      

      If we run this code, we receive output like the following:

      Output

      2020-08-22 18:23:22.233108 datetime.datetime(2020, 8, 22, 18, 23, 22, 233108)

      Note: Generally, your output will contain text related to the current time on your computer. The time on your computer will be different than the time displayed in the sample output.

      In this example, we use the datetime module to get an object representing the current time and bind it to a variable named now. Next, we print out now twice using two different f-strings. In the first f-string, we don’t include any additional modifiers and so Python uses the __str__ representation of the current time.

      In the second example, we add the !r modifier to the end of the expression embedded in the f-string. !r instructs Python to call repr on now to generate a string representation. In general, repr prints debugging information more suitable for the interactive Python interpreter. In this case, we receive details about the datetime object that was bound to now.

      Using Format Specs

      f-strings offer format spec modifiers for additional control of outputted strings. These format spec modifiers are prefixed by a :, for example:

      {expression:format_spec}
      

      The percentage modifier is an example of one available modifier:

      decimal_value = 18.12 / 100.0
      print(f"{decimal_value:.1%}")
      

      If we run this code, we’ll receive output like the following:

      Output

      18.1%

      First, we bind decimal_value to 0.1812 (the result of 18.12 / 100.0). Then, we use an f-string to print out decimal_value as a percentage. The : begins the format spec section. The .1 indicates that we’d like to output the number with 1 decimal point of precision. The % is the type of format spec we’d like to use. The % format spec multiplies the number by 100 and includes a % symbol in the output. So, the final output is 18.12% (0.1812 * 100 rounded to 1 decimal place, and a % symbol).

      Format specs allow you to do more than print out percentages; they are a complex miniature language on their own. They allow you to, for example, include padding characters around an expression or print numbers in scientific notation.

      You can use this section of the Python docs to learn more about Python’s available format specs.

      Dealing with Special Characters

      As we’ve seen, {} characters have special meaning in f-strings. If we want to print a literal { or } character, we’ll need to escape them by adding additional { or } characters. Consider the following example:

      print(f"{{}}")
      

      If we run this code, we’ll receive output like:

      Output

      {}

      In order to print out a literal {}, we needed to double both the { and the } since these characters usually have special meaning.

      Conclusion

      f-strings are a powerful and convenient way to build strings dynamically and concisely in Python. In this tutorial, you have learned how to substitute variables and expressions into f-strings, use type-conversion specifiers, and escape special characters with f-strings.

      The string module exposes additional classes and utilities that we did not cover in this tutorial. Now that you have a baseline, you can use the string module’s documentation to learn more about other available classes and utilities.

      Also, to learn more about Python, check out our Python content page or our How To Code in Python 3 series.



      Source link

      How To Convert Strings to Integers in Python 3


      Strings can be converted to integers by using the int() method.

      If your string does not have decimal places, you’ll most likely want to convert it to an integer by using the int() method.

      Let’s use an example of the user sammy keeping track of lines of code written each day. We may want to manipulate those values with math to provide more interesting feedback for the user, but those values are currently stored in strings:

      lines_yesterday = "50"
      lines_today = "108"
      
      lines_more = lines_today - lines_yesterday
      
      print(lines_more)
      

      Output

      TypeError: unsupported operand type(s) for -: 'str' and 'str'

      Because the two numeric values were stored in strings, we received an error. The operand - for subtraction is not a valid operand for two string values.

      Let’s modify the code to include the int() method that will convert the strings to integers, and allow us to do math with these values that were originally strings.

      lines_yesterday = "50"
      lines_today = "108"
      
      lines_more = int(lines_today) - int(lines_yesterday)
      
      print(lines_more)
      

      Output

      58

      The variable lines_more is automatically an integer, and it is equal to the numeric value of 58 in this example.

      If you want to learn more about converting Python data types, check out How To Convert Data Types in Python 3 as well as our How To Code in Python 3 series.



      Source link