|
| 1 | +b = 'Mahar' # Define a string variable 'b' containing the text 'Mahar'. Single quotes are used. |
| 2 | +c = "Mahar's" # Define a string variable 'c' containing the text 'Mahar's'. Double quotes are used to include a single quote within the string. |
| 3 | +d = '''Mahar |
| 4 | +Hassain kk''' # Define a string variable 'd' with multi-line text using triple quotes. |
| 5 | + |
| 6 | +# Print the values of variables b, c, and d |
| 7 | +print(b) # Output: Mahar |
| 8 | +print(c) # Output: Mahar's |
| 9 | +print(d) # Output: Prints multi-line text: |
| 10 | + # Mahar |
| 11 | + # Hassain kk |
| 12 | + |
| 13 | +# Print the types of the variables b, c, and d using the 'type()' function |
| 14 | +print(type(b), type(c), type(d)) # Output: <class 'str'> <class 'str'> <class 'str'> |
| 15 | + |
| 16 | +#------------------------------------------------------------ |
| 17 | + |
| 18 | +# String slicing and concatenation example |
| 19 | +greetings = "Good Morning, " # Define a string variable 'greetings' containing "Good Morning, " |
| 20 | +name = "mahar" # Define a string variable 'name' containing "mahar" |
| 21 | + |
| 22 | +# Print the type of the variable 'name' using the 'type()' function |
| 23 | +print(type(name)) # Output: <class 'str'> |
| 24 | + |
| 25 | +# Access and print individual characters in the 'name' string |
| 26 | +print(name[0]) # Output: 'm' (the first character of the string) |
| 27 | +print(name[4]) # Output: 'r' (the fifth character of the string, indexing starts at 0) |
| 28 | + |
| 29 | +# Performing string slicing to extract specific portions of the 'name' string |
| 30 | +print(name[0:3]) # Output: 'mah' (characters from index 0 to index 2) |
| 31 | +print(name[1:4]) # Output: 'aha' (characters from index 1 to index 3) |
| 32 | + |
| 33 | +# Attempting to access an index out of range would result in an error |
| 34 | +# print(name[5]) # This line is commented out to prevent an IndexError |
| 35 | + |
| 36 | +# Concatenating two strings and printing the combined result |
| 37 | +print(greetings + name) # Output: 'Good Morning, mahar' |
| 38 | +# Or, we can use a separate variable to store the concatenated string and then print it |
| 39 | +# x = greetings + name |
| 40 | +# print(x) |
| 41 | + |
| 42 | +# Slicing with skip value |
| 43 | +# The syntax for slicing is [start:stop:step] |
| 44 | +ad = name[0:5:2] # Output: "mhr" |
| 45 | +# ad = name[0:5:1] # Output: "mahar" |
| 46 | +# ad = name[0:5:3] # Output: "ma" |
| 47 | +# ad = name[0:4:2] # Output: "mr" |
| 48 | +print(ad) |
| 49 | + |
| 50 | + |
| 51 | + |
| 52 | + |
| 53 | + |
0 commit comments