Use strings data type in Python

1. Define string variables using assignment statements in the format variable name = 'String'.

Assign strings to variables and use them to print output at certain stages of the program. For example: >>> >>> s1 = 'String in single quotes' >>> s1 'String in single quotes' >>> >>> s2 = "String in double quotes" >>> s2 'String in double quotes' >>> Python will show an error if a single quote or apostrophe is used. For example: s1 = 'Hello, this is Tom's laptop' >>> Output: >>> s1 = 'Hello, this is Tom's laptop' File "", line 1 s1 = 'Hello, this is Tom's laptop' The above code would give a SyntaxError: invalid syntax. If you encapsulate the string in double quotes, Python will assign it to the variable s1. For example: >>> s1 = "Hello, this is Tom's laptop" >>> print(s1) Hello, this is Tom's laptop

2. Use the  len() built-in function to count the number of characters in the string.

For example, len () in the snippet below is used to count the numbers of characters in a string, as well as the number of characters in the string variable s. >>> len("a string") 8 >>> >>> s = "a long string" >>> >>> len(s) 13 >>> >>> len("") 0 >>>

3. Use empty strings to create null value variables or to clear string variable values.

For example: >>> >>> s3 = '' # empty string using single quotes >>> s3 '' >>> >>> s4 = "" # empty string using double quotes >>> s4 '' >>> Variables s3 and s4 are still valid strings, despite not containing any characters. This can be verified using the type() function. >>> type(s3) >>> >>> type(s4) >>>

4. Use double quotes when you have single quotation marks inside a string to avoid quote exceptions.

Similarly, wrap the string in single quotes instead of double quotes if you want to print double quotes in a string: >>> >>> print('John says "Hello there!"') John says "Hello there!" >>>

5. Use escape sequences to print special characters, tabs, or line breaks

Escape sequences start with a backslash (  ). Some common escape sequences are: n Newline – Prints a newline character t Tab – Prints a tab character \ Backslash – Prints a backslash (  ) ' Single quote – Prints a single quote " Double quote – Prints a double quote

6. Use the + operator to perform string concatenation and join one or more strings together.

For example: >>> s1 = "This is " + "one complete string" >>> print(s1) This is one complete string >>> >>> s2 = "One " + "really really " + "long string" >>> print(s2) One really really long string >>> Note that the + operator will perform additions when used with numbers, but concatenates strings. >>> >>> 98+57 # + operators add numbers together 155 >>> Python does not allow concatenations of numerical strings or strings with different data types. So, you need to use the str() function to convert them to strings: >>> >>> s = str(100) >>> s '100' >>> type(s) >>>