Skip to content

Instantly share code, notes, and snippets.

@amanrocks11
Last active October 31, 2020 17:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amanrocks11/60fe0cb7638ebfcd293c3cf115c4c5a2 to your computer and use it in GitHub Desktop.
Save amanrocks11/60fe0cb7638ebfcd293c3cf115c4c5a2 to your computer and use it in GitHub Desktop.
New
  1. To check if the substring exists -> .find(sub_string) || .find(sub_string, start_pos, end_pos) Returns -1 if substring does not exists.
  2. This method checks if all the characters of a string are alphanumeric (a-z, A-Z and 0-9). -> str.isalnum()
  3. Swap cases. Will swap cases in the string. -> s.swapcase()
  4. Join the string back -> string = ''.join(l) l can be any iteratable DS like a list.
  5. This method checks if all the characters of a string are digits (0-9)/alphabetical (a-z and A-Z). -> str.isdigit() || str.isalpha()
  6. This method checks if all the characters of a string are lowercase/uppercase characters -> str.islower() || str.isupper()
  7. How to set multiple variables to same value ->
    lower = upper = alpha = digit = False
    variable_name_list = ["a", "b", "c", "d", "e"]
    d = dict.fromkeys(variable_name_list, False)
  8. The any() function returns True if any element of an iterable is True. If not, any() returns False. Example:-
    s = abraKadabra123#$
    print(any(c.isalnum() for c in s))
  9. A string of text can be aligned left, right and center. Inbuild methods are -> .ljust(width) .center(width) .rjust(width) Example:-
    width = 20
    print 'HackerRank'.ljust(width,'-')
    HackerRank---------- 
  10. Textwrap -> provides some convenience functions, as well as TextWrapper. textwrap.wrap(text, width=70, **kwargs) -> wraps a single paragraph in text (a string) so that every line is width characters long at most. It returns a list of output lines. textwrap.fill(text, width=70, **kwargs) -> wraps a single paragraph in text and returns a single string containing the wrapped paragraph. textwrap.shorten(text) -> Collapse and truncate the given text to fit in the given width. First the whitespace in text is collapsed (all whitespace is replaced by single spaces). textwrap.dedent(text) -> Remove any common leading whitespace from every line in text. textwrap.indent(text, prefix, predicate=None) -> Add prefix to the beginning of selected lines in text.
  11. reversed() function returns an iterator that accesses the given sequence in the reverse order.
    seqString = 'geeks'
    print(list(reversed(seqString)))
    Output-> ['s', 'k', 'e', 'e', 'g']
  12. .format()
    "My name is {0}, I'am {1}".format("John",36)
    
    padding = len(bin(number))
    print("{:>{width}}".format(Decimal(i), width = padding))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment