4 Python - Strings.pptx
Document Details
Uploaded by Deleted User
Full Transcript
Strings Formatting and Methods Engr. Hiroyoshi DG. Arai Python Data Types Text Data Type: Mapping Type: – String (str) – Dictionary {dict} Numeric Data Type: Set Types: – Integer (int) – Set {s...
Strings Formatting and Methods Engr. Hiroyoshi DG. Arai Python Data Types Text Data Type: Mapping Type: – String (str) – Dictionary {dict} Numeric Data Type: Set Types: – Integer (int) – Set {set} – Float (float) – Frozen Set (frozenset) – Complex (complex) Binary Types: Boolean Type: – – Bytes (bytes) Boolean (bool) – Byte Array (bytearray) Sequence Types: – – Memory View (memoryview) List [list] – Tuple (tuple) None Type: – Range (range) – None (None) Strings String is a sequence of characters enclosed in quotation marks, either single quotes(‘…’) or double quotes(“…”). It can contain any combination of letters, digits and symbols. It can be concatenated using + operator Strings It is an iterable object, meaning each character has corresponding index. It can be sliced to extract specific portion of the string. Multiline strings are also supported using triple quotes. String is an iterable object Each character in string has index. Meaning each character has a numerical value to represent where each character are located in the string. It is possible to access each individual character using these index. String Index Index starts at 0 from left to right. H e l l o , W o r l d ! 0 1 2 3 4 5 6 7 8 9 10 11 12 Example string “Hello, World!” Strings Index Printing the 3rd and 8th character of the string. >>> varString = “Hello, World!” >>> print(varString) l >>> print(varString) W >>> String Negative Index Last character of the string starts at Index -1 and is numbered from right to left. H e l l o , W o r l d ! -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 Example string “Hello, World!” Strings Negative Index Printing the 2nd to the last character of the string. >>> varString = “Hello, World!” >>> print(varString[-2]) d >>> String Slicing It is possible to return a range of character of a string by using the syntax: >>> varString[start:end:step] – start the target start index of the string – end the target end index of the string – step the amount of skips to the index. (optional: If not specified, defaults to 1) String Slicing >>> name = “Bulacan State University” >>> print(name[2:9]) lacan S >>> print(name[-10:-3]) Univers >>> print(name[0:8:2]) Blcn String Slicing Omitting some argument is also possible. Colons are still required between the arguments. >>> varString[:end] >>> varString[start:] >>> varString[::skip] String Slicing >>> name = “Bulacan State University” >>> print(name[:10]) Bulacan St >>> print(name[12:]) e University >>> print(name[::3]) Bantenei String Formatting Concatenating and casting string is one way to format strings. However, Python has several ways to format a string dynamically allowing for flexible output by replacing placeholders with data associated with it. – % operator –.format() method – f-strings Strings Concatenation Connect two string using the + >>> operator var1 = “Hello” >>> var2 = “World” >>> fullString = var1 + “, “ + var2 + “!” >>> print(fullString) Hello, World! >>> % Operator This is the older way of formatting in Python. % placeholder is used followed by a letter corresponding to the data type. Ending the string with % (data) to format the string separated by comma (,) for multiple data. % Operator >>> name = “BulSU” >>> year = 2024 >>> print(“We are here at %s studying in the year %d” % (name, year)) We are here at BulSU studying in the year 2024 >>> each data type is associated with specific placeholder. – %s string - %f float – %d integer - %x hexadecimal – %o octal - %e exponential % Operator % width or precision specifier formats the string to only print up to specified number using the dot (.) followed by the number of characters. >>> name = “Bulacan State University” >>> pi = 3.141592653589793238 >>> print(“%.5f” % (pi)) 3.14159 >>> print(“%.3s” % (name)) Bul.format() Method The newer and easier way of formatting strings in Python. Curly Braces {} are used as a placeholder. Then ending the string with.format(data) which are separated with comma (,) for multiple data..format() Method >>> name = “BulSU” >>> year = 2024 >>> print(“We are here at {} studying in the year {}”.format(name, year)) We are here at BulSU studying in the year 2024 >>> Using it in a variable: >>> name = “BulSU” >>> year = 2024 >>> msg = “We are here at {} studying in the year {}” >>> print(msg.format(name,year) We are here at BulSU studying in the year 2024 f-string The newest and most convenient way of formatting strings in Python. It was introduced in Python 3.6. the string is prefixed by ‘f’ and the data are already embedded inside the curly braces {data} f-string >>> name = “BulSU” >>> year = 2024 >>> print(f“We are here at {name} studying in the year {year}”) We are here at BulSU studying in the year 2024 >>> Escape Characters There are characters in coding that have special function, for example a quotation mark denotes a string. But what if we need that quotation mark inside a string? To insert these characters, we need to use an escape character which is backslash ‘\’ followed by the character to insert Escape Characters >>> print(“This fruit is called an “Apple””) File “stdin>”, line 1 print(“This fruit is called an “Apple””) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ SyntaxError: invalid syntax. Perhams you forgot a comma? >>> >>> print(“This fruit is called an \“Apple\””) This fruit is called an “Apple” >>> Escape Characters >>> print(“To use a backslash \\ in the string, you need to escape the backslash using \\ like this \\\\”) To use a backslash \ in a string, you need to escape the backslash using \ like this \\ >>> Another way of escaping quote is using different quotation mark. >>> print(‘This fruit is called an “Apple”’) This fruit is called an “Apple” >>> len() function This function can be used to determine the number of characters in a string. This function can be used to most iterable objects to return the number of iteration an object has. String Methods Python has built-in methods for strings to modify or return some data from the string. these methods are used by adding.methodname() at the end of the string or the string variable. String Methods.capitalize() Converts the first character to upper case and the rest is lower case..casefold() Converts string into lower case..center(length, character) Returns a centered string..count(value, start, end) Returns the number of times a specified value appears in the string. String Methods.endswith(value, start, end) returns True if the string ends with the specified value, otherwise False..index(value, start, end) returns the index of the specified value.isalnum() returns True if all characters in the string are alphanumeric. String Methods.isalpha() returns True if all characters in the string are in the alphabet..isnumeric() returns True if all characters in the string are numeric..isspace() returns True if all characters in the string are whitespaces..istitle() returns True if the string follows the rules of a title. String Methods.isupper() returns True if all characters in the string are uppercase..islower() returns True if all characters in the string are lowercase..join(iterable) joins the elements of an iterable to the end of the string..lower() converts a string into lowercase String Methods.replace(oldvalue, newvalue, count) replaces a specified phrase with another specified phrase..split(separator, maxsplit) splits a string into a list of strings..startswith(value, start, end) returns True if the string starts with the specified value, otherwise False. String Methods.strip(characters) removes any leading, and trailing whitespaces or characters..swapcase() swaps cases, lower case becomes uppercase and vice versa..title() converts the first character of each word to upper case.upper() converts a string to all uppercase letters. String Method Samples >>> varString = “helLO, World!” >>> print(varString.lower()) hello, world! >>> print(varString.upper()) HELLO, WORLD! >>> print(varString.replace(“World!”, “Arai”)) helLO, Arai >>> print(varString.title()) Hello, World! >>> String Method Samples >>> message = “BULSU 2024” >>> print(message.isalnum()) False >>> print(message.isalpha()) False >>> print(message.isnumeric()) False >>> print(message.islower()) False >>> print(message.isupper()) True >>>