Store text in string variables to build reusable code or functions in Python.
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”
Hello, this is Tom’s laptop
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
>>> len("a string") 8 >>> >>> s = "a long string" >>> >>> len(s) 13 >>> >>> len("") 0 >>>
>>> >>> 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.
## 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!”
## 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 Python treats escape sequences in strings as special commands. For example, the `t` character inside a string prints a tab character (equivalent to four spaces):
s = “NametAgetMarks”
Name Age Marks
n character inside the string prints a newline character. The newline character isn’t displayed on the screen - instead, it causes the cursor to start printing subsequent characters from the beginning of the next line. For example:
>>> >>> s2 = 'OnenTwonThree' >>> s2 'OnenTwonThree' >>> print(s2) One Two Three >>> ```You can use `'` and `"` escape sequences to print single or double quotation marks in a string. If you use escape sequences to print single or double quotes, it doesn't matter whether the string is wrapped in single or double quotes. For example:
print(‘I’m learning python’)
I’m learning python
print(“John says “Hello there !””)
John says “Hello there !”
```To print a single backslash character ``, use the
\ escape sequence.
>>> >>> s3 = 'C:\Users\Q' >>> s3 'C:\Users\Q' >>> print(s3) C:UsersQ >>>
>>> 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
```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) >>>
The general format is:
string * n ```Where `n` is a number of type `int`. Using the `*` operator repeats the string `n` number of times. For example:
s = "www " * 5 # repeat "www " 5 times
'www www www www www ’
print(“We have got some”, “spam” * 5)
We have got some spamspamspamspamspam
5 * "www " and
"www " * 5 yields the same result.
Python can’t multiply strings by non-int data types and will show an error if you use a different data type for
n. For example:
Traceback (most recent call last): File "", line 1, in TypeError: can't multiply sequence by non-int of type 'str' >>> >>> >>> "www" * 1.5 # n is a float Traceback (most recent call last): File "", line 1, in TypeError: can't multiply sequence by non-int of type 'float' >>>
Type the name of a variable followed by the index of the character inside square brackets
 to access individual characters in a string.
Python stores string characters in sequence, and indexes can be used to refer to the position of a particular character in a string. The first character in a string is at the index 0, the second character is at index 1 and so on. For example:
String: H e l l o Index: 0 1 2 3 4
s1 = “Hello”
s1 # first character
s1 # second character
s1 # third character
s1 # fourth character
s1 # fifth character
```Alternatively, use the
len() function to calculate the length of the string and subtract
1 from it to get the index position of the last character.
>>> >>> quote = "The best is the enemy of the good" >>> >>> quote[len(quote)-1] 'd' >>> ```You can also use negative indexes to access characters from the end of the string. Negative indexes start from -1, so the index position of the last character is -1, the second to last character is -2, and so on. For example:
String H e l l o
Index 0 1 2 3 4
Negative Index -5 -4 -3 -2 -1
>>> >>> s = "Hello" >>> >>> s[-1] # last character 'o' >>> >>> s[-2] # second last character 'l' >>> >>> s[-3] # first character 'l' >>> >>> s[-len(s)] # first character using a combination of the len() function and negative indexes. 'H' >>> ``` ## Use slicing operators `[start_index:end_index]` to get a slice of a string. ``` str_name[start_index:end_index] ````str_name[start_index:end_index]` would return a slice of string starting from index `start_index` to `end_index`. The character at the `end_index` location is not included in the slice. For example: ``` >>> >>> s = "markdown" >>> >>> >>> s[0:3] # returns a string slice starting from index 0 to 3, not including the character at index 3 'mar' >>> >>> >>> s[2:5] # returns a string slice starting from index 2 to 5, not including the character at index 5 'rkd' >>> ```If `end_index` is greater than the length of the string, then the slice operator would return a string slice starting from `start_index` to the end of the string. ``` >>> >>> s[2:len(s)+200] 'rkdown' >>> ````start_index` and `end_index` are optional. If `start_index` is not specified, then slicing will begin at the beginning of the string. If `end_index` is not specified, then it goes on to the end of the string. For example: ``` >>> >>> s[:4] # start slicing from the beginning 'mark' >>> ```In the above expression, the slicing begins at the beginning of the string, so the above expression is the same as `s[0:4]`. ``` >>> >>> s[5:] 'own' >>> ```