String Methods

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

rstrip()

removes any trailing characters (characters at the end of a string), space is the default trailing character to remove String.rstrip(characters): characters are options txt= " Tom " x = txt.rstrip() print("of all the boys", x, "is my favorite") Run—> of all the boys Tom is my favorite Specifying characters: txt = "Tom doesn't" x = txt.rstrip("n't") print(x) Run—> Tom does

isdigit()

returns True if all the characters are digits, otherwise False Exponents are also considered to be a digit txt = "50800" x = txt.isdigit() print(x) Run—> True txt = "5080e" x = txt.isdigit() print(x) Run—> False

isspace()

returns True if all the characters in a string are white spaces txt = " " print(txt.isspace()) Run—>True txt = " s " print(txt.isspace()) Run—> False

istitle()

returns True if all words in a text start with a upper case letter, AND the rest of the word are lower case letters Symbols and numbers are ignored a = "HELLO AND WELCOME" b = "Hello" c = "22 Names" d = "This Is &%^%" print(a.istitle()) print(b.istitle()) print(c.istitle()) print(d.istitle()) False True True True

isidentifier()

returns True if the string is a valid identifier, otherwise False. A string is considered a valid identifier if it only contains alphanumeric letters (a-z) and (0-9), or underscores (_). A valid identified cannot start with a number, or contain any spaces a = "MyFolder" b = "Demo002" c = "2bring" d = "my demo" print(a.isidentifier()) print(b.isidentifier()) print(c.isidentifier()) print(d.isidentifier()) Run—> True True False False

swapcase()

returns a string where all the upper case letters are lower case and vice versa txt = "Hello My Name is PETER" x = txt.swapcase() print(x) Run—> hELLO mY nAME IS peter

title()

returns a string where the first character in every word is upper case If the word contains a number or a symptom, the first letter after that will be converted to upper case txt = "Tom is my 1st love" x = txt.title() print(x) Run—> Tom Is My 1St Love"

translate()

returns a translated string

isprintable()

returns true if all characters in the string are printable Examples of none printable character can be carriage return and line feed \r\n

splitlines()

splits a string into a list. The splitting is done at line breaks string.splitlines(keeplinebreaks): Optional. Specifies if the line breaks should be includes (True), or not (False). Default value is not (False) txt = "Thank you for the music\nWelcome to the jungle" x = txt.splitlines() print(x) Run—> ['Thank you for the music', 'Welcome to the jungle'] txt = "Thank you for the music\nWelcome to the jungle" x = txt.splitlines(True) print(x) Run—> ['Thank you for the music\n', 'Welcome to the jungle']

rsplit()

splits the string into a list, starting from right. If no "max" is specified, this method will return the same as the split method Note: when max is specified, the list will contain the specified number of elements plus one string.rsplit(separator, max) Max specific how many splits to do. Default value is -1, which is "all occurrences" txt = "apple, banana, cherry" x = txt.rsplit(", ") print(x) Run—> ['apple', 'banana', 'cherry'] txt = "apple, banana, cherry" x = txt.rsplit(", ", 1) print(x) Run—> ['apple, banana', 'cherry'] (setting the max parameter to 1, will return a list with 2 elements)

The len() function returns the number of items in an object. When the object is a string, the len() function returns

the number of characters in the string mylist = ["apple", "banana", "cherry"] x = len(mylist) print(x) Run—> 3 vs. mylist = "apple" x = len(mylist) print(x) Run—>5

lstrip() vs. rstrip() txt= " Tom " x = txt.rstrip() print("of all the boys", x, "is my favorite") Run—> of all the boys Tom is my favorite

txt= " Tom " x = txt.lstrip() print("of all the boys", x, "is my favorite") Run—> of all the boys Tom is my favorite

partition() If the specified value is not found, the partition method returns a tuple containing: 1- the whole string, 2- an empty string, 3- an empty string txt= "I could eat bananas all day" x= txt.partition("apples") print(x) Run—>

('I could eat bananas all day', '', '')

What does the find() return if the value is not found?

-1

What is the difference between these two programs: 1.) txt = "Hello, welcome to my world." x = txt.find("e") print(x) 2.) txt = "Hello, welcome to my world." x = txt.find("e", 5, 10) print(x)

1.) Finds the first occurrence of e Run—>1 2.) Searches where in the text e first occurs between the position five and ten? Run—> 8

What do \n do in python?

A line feed means moving one line forward

casefold()

Converts string into lower case

capitalize()

Converts the first character to upper case

what is format_map?

Formats specified values in a string a = {'x':'John', 'y':'Wick'} print("{x}'s last name is {y}".format_map(a)) run—> John's last name is Wick

join()

Joins the elements of an iterable to the end of the string myfriends = ("Vicky", "Alicia", "Joana") x = " ".join(myfriends) print(x)

string.ljust(length, character) What is required?

Only length is required. Character is used to fill the missing space (to the right of the string) txt = "banana" x = txt.ljust(20, "0") print(x, "is my favorite fruit") Run—> banana00000000000000 is my favorite fruit

isalnum()

Returns True if all characters in the string are alphanumeric, meaning (a-z) and (0-9) Example of characters that are not alphanumeric: (space)!#%& etc. word = "Hello world123" print(word.isalnum()) Run—> False (because there is a space) word = "Helloworld123" print(word.isalnum()) Run—> True

islower()

Returns True if all characters in the string are lower case

isupper()

Returns True if all characters in the string are uppers case

maketrans()

Returns a translation table to be used in translations # example dictionary dict = {"a": "123", "b": "456", "c": "789"} string = "abc" print(string.maketrans(dict)) # example dictionary dict = {97: "123", 98: "456", 99: "789"} string = "abc" print(string.maketrans(dict)) Run—> {97: '123', 98: '456', 99: '789'} {97: '123', 98: '456', 99: '789'}

partition()

Returns a tuple where the string is parted into three parts The partition() method searches for a specified string, and splits the string into a tuple containing three elements (one before the specified string, the specified string, and after the specified string) txt = "I could eat bananas all day" x = txt.partition("bananas") print(x) Run—> ('I could eat ', 'bananas', ' all day')

encode()

Returns an encoded version of the string Strings are stored as Unicode, i.e. each character in the string is represented by a code point. So, each string is just a sequence of Unicode code points. For efficient storage of these strings, the sequence of code points are converted into set of bytes. The process is known as encoding. By default, Python users utf-8 encoding

count()

Returns the number of times a specified value occurs in a string

isdecimal()

Returns true if all characters in the string are decimals (0-9). This method is used on Unicode objects

isalpha()

Returns true if all characters in the string are in the alphabet

isnumeric()

Returns true if all characters in the string are numeric

endswith()

Returns true if the string ends with the specified value txt = "geeks for geeks" x = txt.endswith("s") print(x) Run—> True

find()

Searches the string for a specified value and returns the position of where it was found txt = "Hello, welcome to my world." x = txt.find("welcome") print(x) Run—> 7

expandtabs()

Sets the tab size to the specified number of white spaces Default tab size is 8 txt = "I\tl\to\tv\te\tT\to\tm\t!" print(txt.expandtabs(2)) print(txt.expandtabs(4)) Run—> I l o v e T o m ! I l o v e T o m !

center()

The center() method creates and returns a new string which is padded with the specified character string = "geeks for geeks" new_string = string.center(24) print ("After padding String is: ", new_string) Run—> After padding String is: geeks for geeks with 24 characters string = "geeks for geeks" new_string = string.center(24, "*") print ("After padding String is: ", new_string) Run—> After padding String is: ****geeks for geeks***** with 24 characters

What is the only difference between the find() and index() method?

The index method raises an exception if the value is not found

How are placeholders identified?

The placeholders can be identified using named indexes {price}, numbered indexes {0}, or even empty placeholders {}. txt1 = "My name is {fname}, I'am {age}".format(fname = "John", age = 36) txt2 = "My name is {0}, I'am {1}".format("John",36) txt3 = "My name is {}, I'am {}".format("John",36)

What is the difference between a tuple and dictionary?

They are very different data structures. Elements in a tuple have the following properties: - Order is maintained. - They are immutable - They can hold any type, and types can be mixed. - Elements are accessed via numeric (zero based) indices. A Python dictionary is an implementation of a hash table. Elements of a dictionary have the following properties: - Ordering is not guaranteed - Every entry has a key and a value - Elements are accessed using key's values - Entries in a dictionary can be changed. - Key values can be of any hashable type (i.e. not a dict) and types can be mixed while values can be of any type (including other dict's), and types can be mixed Both of these data structures can be created using comprehensions. Examples: Tuple: (1, 'a', (3, 6, 8), 'string') Dictionary: {'foo': [1, 2, 3], 'bar': 'baz'}

ljust()

Will left align the string, using a specified character txt = "banana" x = txt.ljust(20) print(x, "is my favorite fruit") Run—> banana is my favorite fruit (note: in the result there are actually 14 white spaces to the right of the word banana)

What does \r do in python?

\r takes the cursor to the beginning of the line. It is the same effect as in a physical typewriter when you move your carriage to the beginning and overwrite whatever is there

upper()

converts a string into upper case

lower()

coverts a string into lower case

zfill()

fills the string with a specified number of 0 values at the beginning, until it reaches the specified length If the value of the Len parameter is less than the length of the string, no filling is done a = "Tom" b = "Tom is the best" c = "Tom & Julie" print(a.zfill(10)) print(b.zfill(5)) print(c.zfill(15)) Run—> 0000000Tom Tom is the best 0000Tom & Julie

format()

formats the specified value and insert them inside the string's placeholder. The placeholder is defined by using the curly brackets: {} The format method returns the formatted string

Join all items in a dictionary into a string, using the word "TEST" as separator Note: when using a dictionary as an iterable, the returned values are the keys, not the values

myDict = {"name": "John", "country": "Norwway"} myseparator = "TEST" x = myseparator.join(myDict) print(x) Return—> nameTESTcountry

strip()

removes any leading (spaces at the beginning) and trailing (spaces at the end) characters (space is the default leading character to remove) string.strip(characters): Optional. A set of characters to remove as lead/trailing characters txt = ",,,,,rrrttgg....banana.....rttgg,,," x = txt.strip(",rtg.") print(x) Run—> banana

lstrip()

removes any leading characters. Space is the default leading character txt = ",,,,,ssaaww....banana" x = txt.lstrip(",.wsa") print(x) run—> banana However: txt = ",,,,,ssaaww....bananasa.." x = txt.lstrip(",.wsa") print(x) Run—>banana You can add other characters: txt = ",,,,,ssaaww....banana" x = txt.lstrip(",.wsakdkd") print(x) Run—>banana


Set pelajaran terkait

Accounting Test Chapters 5 and 6

View Set

Structural Kinesiology Test 1-Chapter 2 Review Questions {3rd & 4th edition}

View Set

Nazism and the Rise of Hitler MCQ

View Set

Pediatric Success Growth and Development 1

View Set

Macro Econ - Chapt. 16 (unfinished)

View Set

nur 116 - Davis Advantage / Edge - Benign Prostatic Hyperplasia

View Set

Intermediate Accounting CH 16 M/C

View Set