>>> nested_list
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> list=[]
>>> for m in nested_list:
... for t in m:
... list.append(t)
...
>>> list
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
>>>
>>>
>>> nested_list
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> list=[]
>>> for m in nested_list:
... for t in m:
... list.append(t)
...
>>> list
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
>>>
>>>
ConnectTimeout:
import requests
from requests.exceptions import ConnectTimeout
try:
response = requests.get('https://httpbin.org/delay/10', timeout=1)
except ConnectTimeout:
print("The request timed out while trying to connect to the server.")
########################
ConnectionError:
from requests.exceptions import ConnectionError
try:
response = requests.get('1http://thisurldoesnotexist.com')
except ConnectionError:
print("A network problem occurred.")
#################
DependencyWarning:
import warnings
from requests import DependencyWarning
warnings.warn("This is a DependencyWarning", DependencyWarning)
################
FileModeWarning:
import warnings
from requests import FileModeWarning
warnings.warn("This is a FileModeWarning", FileModeWarning)
#####################
HTTPError:
from requests.exceptions import HTTPError
try:
response = requests.get('https://httpbin.org/status/404')
response.raise_for_status()
except HTTPError as http_err:
print(f"HTTP error occurred: {http_err}")
######################################JSONDecodeError:
from requests.exceptions import JSONDecodeError
try:
response = requests.get('https://httpbin.org/get')
data = response.json()
except JSONDecodeError:
print("Failed to decode JSON response.")
#####
NullHandler:
import logging
from requests import NullHandler
logger = logging.getLogger('example_logger')
logger.addHandler(NullHandler())
logger.info('This will not be output anywhere')
############
ReadTimeout:
from requests.exceptions import ReadTimeout
try:
response = requests.get('https://httpbin.org/delay/3', timeout=1)
except ReadTimeout:
print("The server did not send any data in the allotted amount of time.")
https://docs.python.org/3/tutorial/datastructures.html
You can run a Linux command in Python and save the output as a Python variable using the subprocess module. Here’s how you can do it:
subprocess module.subprocess.run() function to execute the command.stdout parameter to subprocess.PIPE.Here’s an example:
pythonimport subprocess
# Run the command and capture the output
result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE, text=True)
# Save the output as a Python variable
output = result.stdout
# Print the output
print(output)
In this example, the ls -l command is executed, and its output is captured and stored in the output variable. The text=True parameter is used to ensure that the output is returned as a string instead of bytes.
subprocess.run(['ls', '-l'], stdout=subprocess.PIPE, text=True):ls -l is passed as a list of arguments.stdout=subprocess.PIPE captures the standard output of the command.text=True ensures that the output is returned as a string.result.stdout contains the output of the command.Here’s another example where we run the uname -a command to get system information:
pythonimport subprocess
# Run the command and capture the output
result = subprocess.run(['uname', '-a'], stdout=subprocess.PIPE, text=True)
# Save the output as a Python variable
output = result.stdout
# Print the output
print(output)
In this example, the uname -a command is executed, and its output is stored in the output variable.
You can also add error handling to capture any errors that might occur during the execution of the command:
pythonimport subprocess
try:
# Run the command and capture the output
result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True)
# Save the output as a Python variable
output = result.stdout
# Print the output
print(output)
except subprocess.CalledProcessError as e:
print(f"Error: {e.stderr}")
In this example, any errors during the execution of the command will be caught, and the error message will be printed. The check=True parameter ensures that an exception is raised if the command exits with a non-zero status.
from math import pi
print(pi)
list=[]
dict={}
for a in str(pi):
list.append(a)
b=set(sorted(list))
print(b)
for c in b:
dict.update({c:list.count(c)})
print(dict)
>>> s="Ambiorix"
s[2] #print index 3 'b' remember index start from 0
s[2:] #remove first 2 line and print everyhing 'biorix'
s[:2] # print first 2 chars 'Am'
s[:-2] #'Ambior' remove last 2 chars
s[-2:] # print the last 2 chargs 'ix'
s[-2] # print the char before the last value 'i'
Get index
>>> for a,b in enumerate(s):
... print(a,b)
...
0 A
1 m
2 b
3 i
4 o
5 r
6 i
7 x
cuando se utiliza la notación de slicing en una cadena (o lista), la sintaxis es:
pythons[start_index : before_end_index]
Donde:
start_index es el índice inicial desde donde se comenzará a extraer la subcadena (o sublista).before_end_index es el índice hasta el cual se extraerá la subcadena (o sublista), pero sin incluir el carácter (o elemento) en esta posición.Por ejemplo, para la cadena s = 'Ambiorix':
s[2:4]
Esto significa que se comenzará a extraer desde el índice 2 y se detendrá justo antes del índice 4. Por lo tanto, los caracteres en los índices 2 y 3 serán seleccionados.
Así, s[2:4] resulta en 'bi', que son los caracteres en los índices 2 y 3 de la cadena s.
Aquí hay un ejemplo generalizado:
ps = 'Ambiorix'print(s[2:5]) # Esto resultará en 'bio'
print(s[:3]) # Esto resultará en 'Amb', empezando desde el inicio hasta antes del índice 3
print(s[4:]) # Esto resultará en 'orix', desde el índice 4 hasta el final
print(s[:]) # Esto resultará en 'Ambiorix', que es la cadena completa
Cada una de estas operaciones de slicing sigue la misma regla: s[start_index : before_end_index].
Here's how you can correctly match the first word in a string:
To match the last word
in a string, you can use regular expressions combined with string manipulation techniques. The approach varies slightly depending on whether you use re.findall, re.search, or another method.
re.findallTo find the last word using re.findall, you would typically capture all words and then select the last one:
\bgob\w*:\b asserts a word boundary before "gob".gob is the specific prefix we are looking for.\w* matches zero or more word characters following "gob".\b\w*te\b:\b asserts a word boundary.\w* matches zero or more word characters preceding "te".te is the suffix we are looking for.\b asserts a word boundary to ensure "te" is at the end of the word.The matches list will contain all words from the text that have the substring "uj" in them. For the provided text, the output will be:
r'\b\w*uj\w*\b':
\b is a word boundary anchor, which ensures that the match occurs at the beginning or end of a word. It's useful if you want to match whole words but is optional if you're just looking for substrings within words.\w* matches any number of word characters (letters, digits, and underscores) before and after the substring uj.uj is the substring you're looking to match within the words.Flags: re.IGNORECASE makes the search case-insensitive.