phml.nodes
All things related to phml node data objects.
1"""phml.nodes 2 3All things related to phml node data objects. 4""" 5 6from .AST import AST 7from .comment import Comment 8from .doctype import DocType 9from .element import Element 10from .literal import Literal 11from .node import Node 12from .parent import Parent 13from .point import Point 14from .position import Position 15from .root import Root 16from .text import Text 17from .types import Properties, PropertyName, PropertyValue 18 19All_Nodes = Root | Element | Text | Comment | DocType | Parent | Node | Literal 20 21__all__ = [ 22 "AST", 23 "Node", 24 "Root", 25 "DocType", 26 "Parent", 27 "Element", 28 "Literal", 29 "Comment", 30 "Text", 31 "Position", 32 "Point", 33 "Properties", 34 "PropertyName", 35 "PropertyValue", 36 "All_Nodes", 37]
17class AST: 18 """PHML ast. 19 20 Contains utility functions that can manipulate the ast. 21 """ 22 23 def __init__(self, tree): 24 if hasattr(tree, "type") and tree.type in ["root", "element"]: 25 self.tree = tree 26 else: 27 raise TypeError("The given tree/root node for AST must be of type `Root` or `Element`") 28 29 def __iter__(self) -> Iterator: 30 from phml.utils import walk # pylint: disable=import-outside-toplevel 31 32 return walk(self.tree) 33 34 def __eq__(self, obj) -> bool: 35 if isinstance(obj, self.__class__): 36 if self.tree == obj.tree: 37 return True 38 return False 39 40 @cached_property 41 def size(self) -> int: 42 """Get the number of nodes in the ast tree.""" 43 from phml.utils import size # pylint: disable=import-outside-toplevel 44 45 return size(self.tree) 46 47 @property 48 def children(self) -> list: 49 """Get access to the ast roots children. 50 Is none if there is no root. 51 """ 52 return self.tree.children if self.tree is not None else None
PHML ast.
Contains utility functions that can manipulate the ast.
11class Node: # pylint: disable=too-few-public-methods 12 """All node values can be expressed in JSON as: string, number, 13 object, array, true, false, or null. This means that the syntax tree should 14 be able to be converted to and from JSON and produce the same tree. 15 For example, in JavaScript, a tree can be passed through JSON.parse(JSON.phml(tree)) 16 and result in the same tree. 17 """ 18 19 position: Position 20 """The location of a node in a source document. 21 The value of the position field implements the Position interface. 22 The position field must not be present if a node is generated. 23 """ 24 25 def __init__( 26 self, 27 position: Optional[Position] = None, 28 ): 29 self.position = position 30 31 @property 32 def type(self) -> str: 33 """Non-empty string representing the variant of a node. 34 This field can be used to determine the type a node implements.""" 35 return self.__class__.__name__.lower()
All node values can be expressed in JSON as: string, number, object, array, true, false, or null. This means that the syntax tree should be able to be converted to and from JSON and produce the same tree. For example, in JavaScript, a tree can be passed through JSON.parse(JSON.phml(tree)) and result in the same tree.
The location of a node in a source document. The value of the position field implements the Position interface. The position field must not be present if a node is generated.
11class Root(Parent): 12 """Root (Parent) represents a document. 13 14 Root can be used as the root of a tree, or as a value 15 of the content field on a 'template' Element, never as a child. 16 """ 17 18 def __init__( 19 self, 20 position: Optional[Position] = None, 21 children: Optional[list] = None, 22 ): 23 super().__init__(position, children) 24 self.parent = None 25 26 def __eq__(self, obj) -> bool: 27 return bool( 28 obj is not None 29 and isinstance(obj, Root) 30 and len(self.children) == len(obj.children) 31 and all(child == obj_child for child, obj_child in zip(self.children, obj.children)) 32 ) 33 34 def stringify(self) -> str: 35 """Build indented html string of documents elements and their children. 36 37 Returns: 38 str: Built html of document 39 """ 40 out = [] 41 out.extend([child.stringify() for child in self.children]) 42 return "\n".join(out) 43 44 def __repr__(self) -> str: 45 return f"root [{len(self.children)}]"
Root (Parent) represents a document.
Root can be used as the root of a tree, or as a value of the content field on a 'template' Element, never as a child.
34 def stringify(self) -> str: 35 """Build indented html string of documents elements and their children. 36 37 Returns: 38 str: Built html of document 39 """ 40 out = [] 41 out.extend([child.stringify() for child in self.children]) 42 return "\n".join(out)
Build indented html string of documents elements and their children.
Returns
str: Built html of document
11class DocType(Node): 12 """Doctype (Node) represents a DocumentType ([DOM]). 13 14 Example: 15 16 ```html 17 <!doctype html> 18 ``` 19 20 Yields: 21 22 ```javascript 23 {type: 'doctype'} 24 ``` 25 """ 26 27 def __init__( 28 self, 29 lang: Optional[str] = None, 30 parent: Optional[Element | Root] = None, 31 position: Optional[Position] = None, 32 ): 33 super().__init__(position) 34 self.parent = parent 35 self.lang = lang or 'html' 36 37 def __eq__(self, obj) -> bool: 38 if obj is None: 39 return False 40 41 if hasattr(obj, "type") and obj.type == self.type: 42 if self.lang == obj.lang: 43 return True 44 return False 45 46 def stringify(self, indent: int = 0) -> str: # pylint: disable=unused-argument 47 """Build indented html string of html doctype element. 48 49 Returns: 50 str: Built html of doctype element 51 """ 52 return f"<!DOCTYPE {self.lang or 'html'}>" 53 54 def __repr__(self) -> str: 55 return f"node.doctype({self.lang or 'html'})"
Doctype (Node) represents a DocumentType ([DOM]).
Example:
<!doctype html>
Yields:
{type: 'doctype'}
46 def stringify(self, indent: int = 0) -> str: # pylint: disable=unused-argument 47 """Build indented html string of html doctype element. 48 49 Returns: 50 str: Built html of doctype element 51 """ 52 return f"<!DOCTYPE {self.lang or 'html'}>"
Build indented html string of html doctype element.
Returns
str: Built html of doctype element
17class Parent(Node): # pylint: disable=too-few-public-methods 18 """Parent (UnistParent) represents a node in hast containing other nodes (said to be children). 19 20 Its content is limited to only other hast content. 21 """ 22 23 def __init__(self, position: Optional[Position] = None, children: Optional[list] = None): 24 super().__init__(position) 25 26 if children is not None: 27 for child in children: 28 child.parent = self 29 30 self.children: list[Element | DocType | Comment | Text] = children or []
Parent (UnistParent) represents a node in hast containing other nodes (said to be children).
Its content is limited to only other hast content.
14class Element(Parent): 15 """Element (Parent) represents an Element ([DOM]). 16 17 A tagName field must be present. It represents the element's local name ([DOM]). 18 19 The properties field represents information associated with the element. 20 The value of the properties field implements the Properties interface. 21 22 If the tagName field is 'template', a content field can be present. The value 23 of the content field implements the Root interface. 24 25 If the tagName field is 'template', the element must be a leaf. 26 27 If the tagName field is 'noscript', its children should be represented as if 28 scripting is disabled ([HTML]). 29 30 31 For example, the following HTML: 32 33 ```html 34 <a href="https://alpha.com" class="bravo" download></a> 35 ``` 36 37 Yields: 38 39 ```javascript 40 { 41 type: 'element', 42 tagName: 'a', 43 properties: { 44 href: 'https://alpha.com', 45 className: ['bravo'], 46 download: true 47 }, 48 children: [] 49 } 50 ``` 51 """ 52 53 def __init__( 54 self, 55 tag: str = "element", 56 properties: Optional[Properties] = None, 57 parent: Optional[Element | Root] = None, 58 startend: bool = False, 59 **kwargs, 60 ): 61 super().__init__(**kwargs) 62 self.properties = properties or {} 63 self.tag = tag 64 self.startend = startend 65 self.parent = parent 66 self.locals = {} 67 68 def __eq__(self, obj) -> bool: 69 return bool( 70 obj is not None 71 and isinstance(obj, Element) 72 and self.tag == obj.tag 73 and self.startend == obj.startend 74 and self.properties == obj.properties 75 and len(self.children) == len(obj.children) 76 and any(child == obj_child for child, obj_child in zip(self.children, obj.children)) 77 ) 78 79 def start_tag(self) -> str: 80 """Builds the open/start tag for the element. 81 82 Note: 83 It will return `/>` if the tag is self closing. 84 85 Returns: 86 str: Built element start tag. 87 """ 88 opening = f"<{self.tag}" 89 90 attributes = [] 91 for prop in self.properties: 92 if isinstance(self.properties[prop], bool) or self.properties[prop] in ["yes", "no"]: 93 if self.properties[prop] == "yes" or self.properties[prop]: 94 attributes.append(prop) 95 else: 96 attributes.append(f'{prop}="{self.properties[prop]}"') 97 if len(attributes) > 0: 98 attributes = " " + " ".join(attributes) 99 else: 100 attributes = "" 101 102 closing = f"{' /' if self.startend else ''}>" 103 104 return opening + attributes + closing 105 106 def end_tag(self) -> str: 107 """Build the elements end tag. 108 109 Returns: 110 str: Built element end tag. 111 """ 112 return f"</{self.tag}>" if not self.startend else None 113 114 def __repr__(self) -> str: 115 out = f"{self.type}(tag: {self.tag}, properties: {self.properties}, children: \ 116{len(self.children)})" 117 return out
Element (Parent) represents an Element ([DOM]).
A tagName field must be present. It represents the element's local name ([DOM]).
The properties field represents information associated with the element. The value of the properties field implements the Properties interface.
If the tagName field is 'template', a content field can be present. The value of the content field implements the Root interface.
If the tagName field is 'template', the element must be a leaf.
If the tagName field is 'noscript', its children should be represented as if scripting is disabled ([HTML]).
For example, the following HTML:
<a href="https://alpha.com" class="bravo" download></a>
Yields:
{
type: 'element',
tagName: 'a',
properties: {
href: 'https://alpha.com',
className: ['bravo'],
download: true
},
children: []
}
53 def __init__( 54 self, 55 tag: str = "element", 56 properties: Optional[Properties] = None, 57 parent: Optional[Element | Root] = None, 58 startend: bool = False, 59 **kwargs, 60 ): 61 super().__init__(**kwargs) 62 self.properties = properties or {} 63 self.tag = tag 64 self.startend = startend 65 self.parent = parent 66 self.locals = {}
79 def start_tag(self) -> str: 80 """Builds the open/start tag for the element. 81 82 Note: 83 It will return `/>` if the tag is self closing. 84 85 Returns: 86 str: Built element start tag. 87 """ 88 opening = f"<{self.tag}" 89 90 attributes = [] 91 for prop in self.properties: 92 if isinstance(self.properties[prop], bool) or self.properties[prop] in ["yes", "no"]: 93 if self.properties[prop] == "yes" or self.properties[prop]: 94 attributes.append(prop) 95 else: 96 attributes.append(f'{prop}="{self.properties[prop]}"') 97 if len(attributes) > 0: 98 attributes = " " + " ".join(attributes) 99 else: 100 attributes = "" 101 102 closing = f"{' /' if self.startend else ''}>" 103 104 return opening + attributes + closing
Builds the open/start tag for the element.
Note
It will return
/>
if the tag is self closing.
Returns
str: Built element start tag.
11class Literal(Node): 12 """Literal (UnistLiteral) represents a node in hast containing a value.""" 13 14 position: Position 15 """The location of a node in a source document. 16 The value of the position field implements the Position interface. 17 The position field must not be present if a node is generated. 18 """ 19 20 value: str 21 """The Literal nodes value. All literal values must be strings""" 22 23 def __init__( 24 self, 25 value: str = "", 26 parent: Optional[Element | Root] = None, 27 position: Optional[Position] = None, 28 ): 29 super().__init__(position) 30 self.value = value 31 self.parent = parent 32 33 def __eq__(self, obj) -> bool: 34 return bool(obj is not None and self.type == obj.type and self.value == obj.value) 35 36 def __repr__(self) -> str: 37 return f"{self.type}(value:{len(self.value)})" 38 39 def get_ancestry(self) -> list[str]: 40 """Get the ancestry of the literal node. 41 42 Used to validate whether there is a `pre` element in the ancestry. 43 """ 44 45 def get_parent(parent) -> list[str]: 46 result = [] 47 48 if parent is not None and hasattr(parent, "tag"): 49 result.append(parent.tag) 50 51 if parent.parent is not None: 52 result.extend(get_parent(parent.parent)) 53 54 return result 55 56 return get_parent(self.parent)
Literal (UnistLiteral) represents a node in hast containing a value.
The location of a node in a source document. The value of the position field implements the Position interface. The position field must not be present if a node is generated.
39 def get_ancestry(self) -> list[str]: 40 """Get the ancestry of the literal node. 41 42 Used to validate whether there is a `pre` element in the ancestry. 43 """ 44 45 def get_parent(parent) -> list[str]: 46 result = [] 47 48 if parent is not None and hasattr(parent, "tag"): 49 result.append(parent.tag) 50 51 if parent.parent is not None: 52 result.extend(get_parent(parent.parent)) 53 54 return result 55 56 return get_parent(self.parent)
Get the ancestry of the literal node.
Used to validate whether there is a pre
element in the ancestry.
6class Comment(Literal): 7 """Comment (Literal) represents a Comment ([DOM]). 8 9 Example: 10 ```html 11 <!--Charlie--> 12 ``` 13 """ 14 15 def stringify(self, indent: int = 0) -> str: 16 """Build indented html string of html comment. 17 18 Returns: 19 str: Built html of comment 20 """ 21 lines = [line.lstrip() for line in self.value.split("\n") if line.strip() != ""] 22 if len(lines) > 1: 23 start = f"{' ' * indent}<!--{lines[0]}" 24 end = f"{' ' * indent}{lines[-1]}-->" 25 for i in range(1, len(lines) - 1): 26 lines[i] = (' ' * indent) + lines[i].strip() 27 lines = [start, *lines[1:-1], end] 28 return "\n".join(lines) 29 return ' ' * indent + f"<!--{self.value}-->" 30 31 def __repr__(self) -> str: 32 return f"literal.comment(value: {self.value})"
Comment (Literal) represents a Comment ([DOM]).
Example:
<!--Charlie-->
15 def stringify(self, indent: int = 0) -> str: 16 """Build indented html string of html comment. 17 18 Returns: 19 str: Built html of comment 20 """ 21 lines = [line.lstrip() for line in self.value.split("\n") if line.strip() != ""] 22 if len(lines) > 1: 23 start = f"{' ' * indent}<!--{lines[0]}" 24 end = f"{' ' * indent}{lines[-1]}-->" 25 for i in range(1, len(lines) - 1): 26 lines[i] = (' ' * indent) + lines[i].strip() 27 lines = [start, *lines[1:-1], end] 28 return "\n".join(lines) 29 return ' ' * indent + f"<!--{self.value}-->"
Build indented html string of html comment.
Returns
str: Built html of comment
8class Text(Literal): 9 """Text (Literal) represents a Text ([DOM]). 10 11 Example: 12 13 ```html 14 <span>Foxtrot</span> 15 ``` 16 17 Yields: 18 19 ```javascript 20 { 21 type: 'element', 22 tagName: 'span', 23 properties: {}, 24 children: [{type: 'text', value: 'Foxtrot'}] 25 } 26 ``` 27 """ 28 29 @cached_property 30 def num_lines(self) -> int: 31 """Determine the number of lines the text has.""" 32 return len([line for line in self.value.split("\n") if line.strip() != ""]) 33 34 def stringify(self, indent: int = 0) -> str: 35 """Build indented html string of html text. 36 37 Returns: 38 str: Built html of text 39 """ 40 if self.parent is None or not any( 41 tag in self.get_ancestry() for tag in ["pre", "python", "script", "style"] 42 ): 43 lines = [line.lstrip() for line in self.value.split("\n") if line.strip() != ""] 44 for i, line in enumerate(lines): 45 lines[i] = (' ' * indent) + line 46 return "\n".join(lines) 47 return self.value 48 49 def __repr__(self) -> str: 50 return f"literal.text('{self.value}')"
Text (Literal) represents a Text ([DOM]).
Example:
<span>Foxtrot</span>
Yields:
{
type: 'element',
tagName: 'span',
properties: {},
children: [{type: 'text', value: 'Foxtrot'}]
}
34 def stringify(self, indent: int = 0) -> str: 35 """Build indented html string of html text. 36 37 Returns: 38 str: Built html of text 39 """ 40 if self.parent is None or not any( 41 tag in self.get_ancestry() for tag in ["pre", "python", "script", "style"] 42 ): 43 lines = [line.lstrip() for line in self.value.split("\n") if line.strip() != ""] 44 for i, line in enumerate(lines): 45 lines[i] = (' ' * indent) + line 46 return "\n".join(lines) 47 return self.value
Build indented html string of html text.
Returns
str: Built html of text
11class Position: 12 """Position represents the location of a node in a source file. 13 14 The `start` field of `Position` represents the place of the first character 15 of the parsed source region. The `end` field of Position represents the place 16 of the first character after the parsed source region, whether it exists or not. 17 The value of the `start` and `end` fields implement the `Point` interface. 18 19 The `indent` field of `Position` represents the start column at each index 20 (plus start line) in the source region, for elements that span multiple lines. 21 22 If the syntactic unit represented by a node is not present in the source file at 23 the time of parsing, the node is said to be `generated` and it must not have positional 24 information. 25 """ 26 27 def __init__(self, start: Point, end: Point, indent: Optional[int] = None): 28 self.start = start 29 self.end = end 30 31 if indent is not None and indent < 0: 32 raise IndexError(f"Position.indent value must be >= 0 or None but was {indent}") 33 34 self.indent = indent 35 36 def __eq__(self, obj) -> bool: 37 return bool( 38 obj is not None 39 and isinstance(obj, Position) 40 and self.start == obj.start 41 and self.end == obj.end 42 ) 43 44 def __repr__(self) -> str: 45 indent = f" ~ {self.indent}" if self.indent is not None else "" 46 return f"<{self.start}-{self.end}{indent}>" 47 48 def __str__(self) -> str: 49 return repr(self)
Position represents the location of a node in a source file.
The start
field of Position
represents the place of the first character
of the parsed source region. The end
field of Position represents the place
of the first character after the parsed source region, whether it exists or not.
The value of the start
and end
fields implement the Point
interface.
The indent
field of Position
represents the start column at each index
(plus start line) in the source region, for elements that span multiple lines.
If the syntactic unit represented by a node is not present in the source file at
the time of parsing, the node is said to be generated
and it must not have positional
information.
6class Point: 7 """Represents one place in a source file. 8 9 The line field (1-indexed integer) represents a line in a source file. The column field 10 (1-indexed integer) represents a column in a source file. The offset field (0-indexed integer) 11 represents a character in a source file. 12 """ 13 14 def __init__(self, line: int, column: int, offset: Optional[int] = None): 15 if line < 0: 16 raise IndexError(f"Point.line must be >= 0 but was {line}") 17 18 self.line = line 19 20 if column < 0: 21 raise IndexError(f"Point.column must be >= 0 but was {column}") 22 23 self.column = column 24 25 if offset is not None and offset < 0: 26 raise IndexError(f"Point.offset must be >= 0 or None but was {line}") 27 28 self.offset = offset 29 30 def __eq__(self, obj) -> bool: 31 return bool( 32 obj is not None 33 and isinstance(obj, self.__class__) 34 and self.line == obj.line 35 and self.column == obj.column 36 ) 37 38 def __repr__(self) -> str: 39 return f"point(line: {self.line}, column: {self.column}, offset: {self.offset})" 40 41 def __str__(self) -> str: 42 return f"{self.line}:{self.column}"
Represents one place in a source file.
The line field (1-indexed integer) represents a line in a source file. The column field (1-indexed integer) represents a column in a source file. The offset field (0-indexed integer) represents a character in a source file.
14 def __init__(self, line: int, column: int, offset: Optional[int] = None): 15 if line < 0: 16 raise IndexError(f"Point.line must be >= 0 but was {line}") 17 18 self.line = line 19 20 if column < 0: 21 raise IndexError(f"Point.column must be >= 0 but was {column}") 22 23 self.column = column 24 25 if offset is not None and offset < 0: 26 raise IndexError(f"Point.offset must be >= 0 or None but was {line}") 27 28 self.offset = offset
str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.
Encode the string using the codec registered for encoding.
encoding The encoding in which to encode the string. errors The error handling scheme to use for encoding errors. The default is 'strict' meaning that encoding errors raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.
Return a copy with all occurrences of substring old replaced by new.
count Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are replaced.
Return a list of the substrings in the string, using sep as the separator string.
sep The separator used to split the string.
When set to None (the default value), will split on any whitespace
character (including \\n \\r \\t \\f and spaces) and will discard
empty strings from the result.
maxsplit Maximum number of splits (starting from the left). -1 (the default value) means no limit.
Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.
Return a list of the substrings in the string, using sep as the separator string.
sep The separator used to split the string.
When set to None (the default value), will split on any whitespace
character (including \\n \\r \\t \\f and spaces) and will discard
empty strings from the result.
maxsplit Maximum number of splits (starting from the left). -1 (the default value) means no limit.
Splitting starts at the end of the string and works to the front.
Concatenate any number of strings.
The string whose method is called is inserted in between each given string. The result is returned as a new string.
Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
Return a capitalized version of the string.
More specifically, make the first character have upper case and the rest lower case.
Return a version of the string where each word is titlecased.
More specifically, words start with uppercased characters and all remaining cased characters have lower case.
Return a centered string of length width.
Padding is done using the specified fill character (default is a space).
S.count(sub[, start[, end]]) -> int
Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return a copy where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
S.find(sub[, start[, end]]) -> int
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
Partition the string into three parts using the given separator.
This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing the original string and two empty strings.
S.index(sub[, start[, end]]) -> int
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
Return a left-justified string of length width.
Padding is done using the specified fill character (default is a space).
Return a copy of the string with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
S.rfind(sub[, start[, end]]) -> int
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
S.rindex(sub[, start[, end]]) -> int
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
Return a right-justified string of length width.
Padding is done using the specified fill character (default is a space).
Return a copy of the string with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
Partition the string into three parts using the given separator.
This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing two empty strings and the original string.
Return a list of the lines in the string, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends is given and true.
Return a copy of the string with leading and trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
Convert uppercase characters to lowercase and lowercase characters to uppercase.
Replace each character in the string using the given translation table.
table Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.
The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.
S.startswith(prefix[, start[, end]]) -> bool
Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.
S.endswith(suffix[, start[, end]]) -> bool
Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.
Return a str with the given prefix string removed if present.
If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.
Return a str with the given suffix string removed if present.
If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.
Return True if all characters in the string are ASCII, False otherwise.
ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.
Return True if the string is a lowercase string, False otherwise.
A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.
Return True if the string is an uppercase string, False otherwise.
A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.
Return True if the string is a title-cased string, False otherwise.
In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.
Return True if the string is a whitespace string, False otherwise.
A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.
Return True if the string is a decimal string, False otherwise.
A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.
Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there is at least one character in the string.
Return True if the string is a numeric string, False otherwise.
A string is numeric if all characters in the string are numeric and there is at least one character in the string.
Return True if the string is an alphabetic string, False otherwise.
A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.
Return True if the string is an alpha-numeric string, False otherwise.
A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.
Return True if the string is a valid Python identifier, False otherwise.
Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as "def" or "class".
Return True if the string is printable, False otherwise.
A string is printable if all of its characters are considered printable in repr() or if it is empty.
Pad a numeric string with zeros on the left, to fill a field of the given width.
The string is never truncated.
S.format(args, *kwargs) -> str
Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces ('{' and '}').
S.format_map(mapping) -> str
Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces ('{' and '}').
Return a translation table usable for str.translate().
If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.