Strings

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

Given the string 'hello' give an index command that returns 'e'. Enter your code in the cell below: s = 'hello' # Print out 'e' using indexing s[1] # position/location 'e'

-A string in Python is a sequence of characters. It is a derived data type. Strings are immutable. This means that once defined, they cannot be changed. -We create a variable for string and then assigned it with a value of 'hello'. s = 'hello' (string) -An index is a position of an individual character or element in a list, tuple, or string. The index value always starts at zero and ends at one less than the number of items. -by using indexing ['h','e','l','l','o'] we can print out the position/location of 'e' which is s[1].

Given the string 'hello', give two methods of producing the letter 'o' using indexing. Method 1: s ='hello' # Print out the 'o' s[-1] 'o' Method 2: s[4] 'o'

-An index is a position of an individual character or element in a list, tuple, or string. The index value always starts at zero and ends at one less than the number of items. -Method 1 which is s[-1]. Since we know that 'o' is at the end of the string, we can provide the negative one (-1) index number so that we can tell python it starts counting from the end of the string or sequence. -Method 2 which is s[4]. For the string ['h','e','l','l','o'] by counting all the from the beginning which is zero (0 = 'h') and then we end at four ( 4 = 'o') which is the last number for the word 'hello'.

Reverse the string 'hello' using slicing: s ='hello' # Reverse the string using slicing s[::-1] # start, end, steps 'olleh'

-Slicing is the extraction of a part of a string, list, or tuple. It enables users to access the specific range of elements by mentioning their indices. -Syntax for slicing is the object [start:stop:step] (default is zero) "Start" specifies the starting index of a slice "Stop" specifies the ending element of a slice You can use one of these if you want to skip certain items. -To reverse a string we use a negative step to reverse the elements of a data structure. -In the example we do not provide the first two numbers to indicate that it will start from the beginning and end all the way to the end but going other the direction that is why we use negative -1.


Ensembles d'études connexes

Patho Chapter 16 Q's Mostly fill-in the blank

View Set

Financial Management Exam 1 Review

View Set

Chapter 1: Intro to Employee Training and Development

View Set

Psych. Exam 2 (Section: Thinking and Intelligence)

View Set

Sociology Chapter 14 Capitalism And The Economy

View Set

Næringsstoffer kap 4 + litt av kap 5

View Set