#!/usr/bin/python3 # -*- coding: utf-8 -*- """ This is a special string, a module docstring summary line. This is the body of the module docstring. """ from typing import List def funcy_strings() -> None: """ This is a special string, a function docstring summary line. This is the body of the function docstring. """ print("A string literal") help(funcy_strings) print(funcy_strings.__doc__) "This string is a string literal" print("This string is a string literal") """ This multi-line string is actually string literal """ print( """ This multi-line string is actually string literal """ ) regular_ml_string: str = """Hey this inserts newlines""" # Note the \n in the strings, when we trace it! regular_string: str = "Hey\nthis\ninserts\nnewlines" print(regular_string) print(regular_ml_string) print(regular_ml_string == regular_string) print(regular_ml_string is regular_string) """ Raw Strings, multi-line strings, and regular strings do not produce different strings, since they're just another method of entering strings. You can place an r before the beginning quotation mark of a string to make it a raw string. A raw string completely ignores all escape characters and prints any backslash that appears in the string. It's just a way of entering the string, not a different string upon storage though! For example, enter the following into the interactive shell: """ raw_string: str = r"""That is Carol's cat.""" regular_ml_string = """That is Carol's cat.""" regular_string = "That is Carol's\ncat." print(raw_string) print(regular_ml_string) print(regular_string) print(raw_string == regular_ml_string == regular_string) print(raw_string is regular_ml_string is regular_string) raw_string = r"""That is Carol's \n cat.""" regular_ml_string = """That is Carol's \\n cat.""" regular_string = "That is Carol's\n\\n cat." print(raw_string) print(regular_ml_string) print(regular_string) print(raw_string == regular_ml_string == regular_string) print(raw_string is regular_ml_string is regular_string) """ Building longer strings from strings and variables (str or non-str), can be done is a variety of ways: somevar: str = "anotherstr" 1. Basic + operator: "somestr " + somevar 2. Classic C-style printf % format string operator "somestr %s" % (somevar) 3. Python str.format string function "somestr {}".format(somevar) 4. f'ing' nice f'strings' f"somestr {somevar}" """ somevar: str = "anotherstr" print("somestr " + somevar) print("somestr %s" % (somevar)) print("somestr {}".format(somevar)) print(f"somestr {somevar}") # 1. Basic + operator # This is often the most readable way to format a big string from substrings. space: str = " " helloworld: str = "hello" + space + "world" print(helloworld) print("hello" + space + "world") # Basic help on + operator: import operator help(operator.add) # str quacks like a duck, so can be added: help(str.__add__) # 2. Classic C-style format string """ Python uses C-style string formatting to create new, formatted strings. The "%" operator is used to format a set of variables enclosed in a tuple, together with a format string, which contains normal text together with "argument specifiers", special symbols like "%s" and "%d". The format operator, % allows us to construct strings, replacing parts of the strings with the data stored in variables. When applied to integers, % is the modulus operator. But when the first operand is a string, % is the format operator. The first operand is the format string, which contains one or more format sequences that specify how the second operand is formatted. The result is a string. For example, the format sequence "%d" means that the second operand should be formatted as an integer (d stands for "decimal"). %s String (or any object with a string representation, like numbers) %d Integers %f Floating point numbers %.f Floating point numbers with a fixed amount of digits to the right of the dot. and many more... """ myfloat: float = 1.44444 print("%d" % myfloat) name: str = "Taylor" print(len(name)) print("Hello, %s!" % name) name = "Mary" age: float = 23.56 print("%s is %.1f years old." % (name, age)) mylist: List[int] = [1, 2, 3] print("A list: %s" % mylist) # Further help on % strings # https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting # 3. str.format() method # This is another type of format string, newer than % print("{} and {}".format("thing", "thing2")) print('We are the {} who say "{}!"'.format("knights", "Ni")) # positional notation allows repeats: print("{0} and {1} and {0} again".format("spam", "eggs")) # spam and eggs # Mixing positional and named arguments: print( "Story of {0}, {1}, and {other} and {other} again.".format( "Bill", "Jane", other="Georg" ) ) # Named postions. variable: str = "hat" print("The {animal} in the {headwear}".format(animal="cat", headwear=variable)) """ In most of the cases the syntax is similar to the old "%"-formatting, with the addition of the "{}" and with ":" used instead of "%". For example, "'%03.2f'" can be translated to "'{:03.2f}'". """ myfloat = 1.44444 print("{:03.2f}".format(myfloat)) # You can get help on .format strings: help(format) help("FORMATTING") # https://docs.python.org/3/library/stdtypes.html#str.format # https://docs.python.org/3/library/string.html#formatstrings # https://docs.python.org/3/library/string.html#formatspec # 4. f-strings # You can also format using f-strings or formatted string literals # This is the newest and fastest method. name = "Reiko" print(f"She said her name is {name}.") # => "She said her name is Reiko" # You can basically put any Python statement inside the braces, # and it will be output in the string. print(f"{name} is {len(name)} characters long.") # => "Reiko is 5 characters long." # Multi-line f"strings are great" print( f"this long thing that would be ugly before " f"is " f"on " f"one " f"line that would have required a more cumbersome method before" ) # Formatting works this way too: myfloat = 1.44444 print(f"{myfloat:03.2f}") # Get extra help on f-strings # https://docs.python.org/3/reference/lexical_analysis.html#f-strings # Remember, the all the string methods are just ways of constructing strings. # They eventually produce the same strings in the end though! """ Strings as containers of characters """ # %% Strings can be considered immutable containers of characters # They obey all the same indexing rules, # and have similar functions to other containers # A string literal can be treated like an tuple of characters print("This is a string"[1]) # => 'h' str1: str = "Hello World!" print(str1) # A string variable can be treated like an tuple of characters print(str1) # Prints complete string print(str1[0]) # Prints first character of the string print(str1[2:5]) # Prints characters starting from 3rd to 5th print(str1[2:]) # Prints string starting from 3rd character print(str1 * 2) # Prints string two times print(str1 + "TEST") # Prints concatenated string var1: str = "Hello World!" var2: str = "Python is awesome" print("var1[0]: ", var1[0]) print("var2[1:5]: ", var2[1:5]) # legnth of string print(len(var1)) # If it quacks like a duck, it's a duck! print(var1.__len__()) # Basic string operations and functions astring: str = "Hello world of python!" print(len(astring)) print(astring.index("o")) print(astring.count("l")) # Simple index print(astring[3:7]) # The general form is [start:stop:step] print(astring[3:7:2]) # Reverse a string (or any ordered container where slicing works) print(astring[::-1]) print(astring.upper()) print(astring.lower()) print(astring.startswith("Hello")) print(astring.endswith("asdfasdfasdf")) """ There are a number of handy methods: isalpha() Returns True if the string consists only of letters and isn’t blank isalnum() Returns True if the string consists only of letters and numbers and is not blank isdecimal() Returns True if the string consists only of numeric characters and is not blank isspace() Returns True if the string consists only of spaces, tabs, and newlines and is not blank istitle() Returns True if the string consists only of words that begin with an uppercase letter followed by only lowercase letters """ print("hello".isalpha()) print("hello123".isalpha()) print("hello123".isalnum()) print("hello".isalnum()) print("123".isdecimal()) print(" ".isspace()) print("This Is Title Case".istitle()) print("This Is Title Case 123".istitle()) print("This Is not Title Case".istitle()) print("This Is NOT Title Case Either".istitle()) # Note: splitting on spaces is an extremely common thing to do! now_an_array_of_words: List[str] = astring.split(" ") print(now_an_array_of_words) help(str.split) # To join them back together, pick your 'serarator'.join() print("".join(now_an_array_of_words)) print(" ".join(now_an_array_of_words)) print("-".join(now_an_array_of_words)) print("_".join(now_an_array_of_words)) help(str.join) # You can get further help on the str functions: help(str)