This is the fourth day of my participation in the November Gwen Challenge. See details: The last Gwen Challenge 2021.

Runtime environment

Python: 3.8.3 jupyter-notebook: 6.4.0

Note: This example can be run directly on jupyter-Notebook, but PyCharm requires print at the end of the code.


Input output function

print()

Print () is definitely the most used function. It can print directly, specify interval/trailing characters, save the output to a specified file (application: logging automatic script exception information), and so on. Here are some common uses.

1️ direct output

print('hello world')
Copy the code
Output: hello world


2️ specifying interval character SEP

print('A'.'B'.'C', sep=' Python ')
Copy the code
Output: A Python B Python C


3️ designated ending character

print('hello'.'world', end='Python')
Copy the code
Output: hello worldPython


4️ store the output content in outfile.txt

print('hello'.'world', sep=' ', file=open('outfile.txt'.'w', encoding='utf-8'))
Copy the code


input()

Input () accepts user input and saves it as a string.

name = input('name:')
Copy the code

jupyter notebookThe effect may be different from other editors, but the operation is to enter, press “enter”.


Get data type

type()

Type () returns the data type of the specified value.

type([1.2])
Copy the code
Output: the list


isintance()

Isintance () checks whether the passed value is of the specified type and returns True or False.

isinstance('Python New Horizons'.str)
Copy the code
Output: True,


String manipulation

str()

STR () converts the specified value to a string type.

str(1.23)
Copy the code
Output: ‘1.23’


eval()

Eval () converts a string into a valid expression to evaluate or evaluate the result. Strings can be converted to lists, tuples, dictionaries, sets, etc.

res = eval("{'name': 'Python'}")
type(res)
Copy the code
Output: dict


str.capitalize()

Capitalize () returns the first letter in the string capitalized and the rest of the lowercase string

cap_str = 'Python New Horizons'.capitalize()
cap_str
Copy the code
Output: ‘Python New Horizons’


str.center()

Center () returns a centered string of the specified width, with the left and right portions filled with the specified characters.

  • widthLength:
  • fillchar: Empty partially filled character. Default is space
center_str = 'Python New Horizons'.center(15."!")
center_str
Copy the code
Output: ‘!!!!!! Python New Horizons!! ‘


str.count()

Str.count (sub, start, end) returns the number of occurrences of sub in STR. The range can be specified by [start, end], otherwise the entire string is searched by default.

  • Sub: substring
  • Start: indicates the start index. The default value is 0
  • End: The index of the end, which is the length of the string by default
name = 'python python'
# count the number of 'p' occurrences by default for the first time
Start =1; start=1;
name.count('p'), name.count('p'.1)
Copy the code
Output: (2, 1)


str.find() & str.rfind()

1️ find() scans the string from left to right and returns the subscript of the first occurrence of sub. You can specify a range with [start, end], otherwise the entire string is searched by default. Returns -1 if no string is found.

  • Sub: substring
  • Start: indicates the location to start the search. The default value is 0
  • End: The location where the search ends. Default is the length of the string
name = 'Python'
Find the first occurrence of the subscript of 'Py' at the default range
# specify start=1 a second time, starting with the second character.
name.find('Py'), name.find('Py'.1)
Copy the code
Output: (0, 1)


2️ retail rfind is similar to find() except that scanning starts from right to left, that is, from the end of string to the beginning of string.

name = 'Python'
name.rfind('Py'), name.rfind('Py'.1)
Copy the code
Output: (0, 1)


str.index() & str.rindex()

1️ retail index() and find() are the same, the only difference is that an error will be reported if sub cannot be found.

Sample 🅰 ️

name = 'Python'
name.index('Py'.0)
Copy the code
Output: 0


Example: b:

name = 'Python'
name.index('Py'.1)
Copy the code
Output: ValueError: substring not found


2️ retail index() and index() have the same usage, but starting from the right, its query is the same as index().

name = 'Python'
name.rindex('Py'.0)
Copy the code
Output: 0


str.isalnum()

Isalnum () checks whether all characters in the string are letters (which can be Chinese characters) or numbers, True, False, and False for empty strings.

Sample 🅰 ️

'Python New Horizons'.isalnum()
Copy the code
Output: True,


Example: b:

'Python-sun'.isalnum()
Copy the code
Output: False
The '-'Is a symbol, so returnFalse.


str.isalpha()

Isalpha () checks whether all characters in the string are letters (which can be Chinese characters), True, False, and False for empty strings.

Sample 🅰 ️

'Python New Horizons'.isalpha()
Copy the code
Output: True,


Sample 🅱 ️

'123Python'.isalpha()
Copy the code
Output: False
It contains a number, returnFalse


str.isdigit()

Isdigit () determines whether all characters in a string are digits (Unicode digits, byte digits (single-byte), full-corner digits (double-byte), Roman digits), True, False, and False for empty strings.

Sample 🅰 ️

'four 123'.isdigit()
Copy the code
Output: False

This contains a Chinese character number. Return False


Sample 🅱 ️

b'123'.isdigit()
Copy the code
Output: True,

Byte The byte number returns True.


str.isspace()

String contains only Spaces (\n, \r, \f, \t, \v), True, False, empty string returns False.

symbol meaning
\n A newline
\r enter
\f Change the page
\t Horizontal tabs
\v Vertical TAB character
' \n\r\f\t\v'.isspace()
Copy the code
Output: True,


str.join()

Join (iterable) combines all elements of iterable (which must be strings) into a new string using the specified string as the delimiter.

', '.join(['Python'.'Java'.'C'])
Copy the code
Output: ‘Python, Java, C’


str.ljust() & str.rjust()

1️ discount () returns a left-aligned string of the specified width

  • widthLength:
  • fillchar: Fills the left part of the left part of the character. Default is space
ljust_str = 'Python New Horizons'.ljust(15."!")
ljust_str
Copy the code
Output: ‘Python New Horizons!!!!!! ‘


2️ rjust() returns a right-aligned string of the specified width, the opposite of the ljust operation.

  • widthLength:
  • fillchar: Fills the left blank part of the character. Default is space
rjust_str = 'Python New Horizons'.rjust(15."!")
rjust_str
Copy the code
Output: ‘!!!!!!!!!!!!!!! Python New Horizons’


str.lower() & str.islower()

1️ lower() convert the specified string to lower case.

lower_str = 'Python New Horizons'.lower()
lower_str
Copy the code
Output: ‘Python New Horizons’


2️ discount () Determine whether all case-sensitive characters of string are lowercase, True, False, empty string or non-case-sensitive characters in string return False.

'python-sun'.islower()
Copy the code
Output: True,

The ‘python-sun’ case-sensitive characters are ‘pythonsun’ and are all lowercase, so return True.


str.lstrip() & str.rstrip() & str.strip()

1️ lstrip() will be intercepted on the left side of the string according to the specified character, if the default interception is not specified, the empty (space, \r, \n, \t, etc.) part on the left side will be intercepted.

name = '+++Python New Horizons +++'
name.lstrip('+')
Copy the code
Output: ‘Python new Horizons +++’


2️ rstrip() is similar to lstrip(), only intercepting the content on the right side.

name = '+++Python New Horizons +++'
name.rstrip('+')
Copy the code
Output: ‘+++Python new Horizons’


3️ strip() is actually the combination of lstrip() and rstrip(), which intercepts the specified characters on both sides of the string.

name = '+++Python New Horizons +++'
name.strip('+')
Copy the code
Output: ‘Python New Horizons’


str.split() & str.splitlines()

1️ str.split(sep=None, maxsplit=-1) Use sep as separator to split the string and return a list of words in the string.

  • Seq:A separator used to split a string.None(Default) splits by any whitespace and returns no whitespace.
  • Maxsplit: Specifies the maximum number of splits. -1(default value) indicates no limit.
split_str = 'P y t h o n new field '
split_str.split(maxsplit=2)
Copy the code
Output: [‘P’, ‘y’,’t h o n ‘]

Use the default space for splitting and set the maximum number of splits to 2


2️ str.splitlines Returns a row table in strings separated by lines (‘\r’, \n’, ‘\r\n’) and returns the separated list. It takes only one parameter, Keepends, to indicate whether to keep newlines in the result, False (default) not, True.

Sample 🅰 ️

split_str = 'P\ny\r t h o n '
split_str.splitlines()
Copy the code
Output: [‘P’, ‘y’, ‘t h o n ‘]


Sample 🅱 ️

split_str = 'P\ny\r t h o n '
split_str.splitlines(keepends=True)
Copy the code
Output: [‘P\n’, ‘y\r’, ‘t h o n’]


str.startswith() & str.endswith

1️ startswith(prefix[, start[, end]]) check whether the string startswith the specified substring substr, True, False, empty string will report an error. If start and end are specified, check within the specified range.

startswith_str = 'Python New Horizons'
startswith_str.startswith('thon'.2)
Copy the code
Output: True,
Detection starts at the third character


2️ str.endswith(suffix[, start[, end]]) is the same as startswith, the difference is to check whether the string endswith a specified substring, True, False, empty string will report an error.

endswith_str = 'Python New Horizons'
endswith_str.endswith('thon'.0.6)
Copy the code
Output: True,
Starting at the first character and ending at the seventh character, note that the range is the same as string slicing: it is closed before opening.


str.title() & str.istitle()

1️ retail title() returns the first letter of every word in the string uppercase.

title_str = 'python新视野 python新视野'.title()
title_str
Copy the code
Output: ‘Python new Horizons’


2️ discount () Determine whether the string meets the first letter of every word capitalized, True, False, empty string returns False.

'Abc Def '.istitle()
Copy the code
Output: True,


str.upper() & str.isupper()

1️ upper() convert letters in a specified string to uppercase.

upper_str = 'Python New Horizons'.upper()
upper_str
Copy the code
Output: ‘PYTHON New Horizons’


2️ disupper () Determine whether all case-sensitive characters of string are uppercase, True, False, empty string or non-case-sensitive characters in string return False.

'PYTHON-SUN'.isupper()
Copy the code
Output: True,

That’s all for this article, if it feels good.❤ Just like it before you go!! ❤

For those who are new to Python or want to learn Python, you can search “Python New Horizons” on wechat to communicate and learn with others. They are all beginners. Sometimes a simple question is stuck for a long time, but others may suddenly realize it with a little help.