HELLO

I WANT TO LEARN PHP

What is GEEK

Buddha Community

HELLO

PLEASE HELP ME

Matteo Gioioso

1659433662

PHP Tutorial for Beginners - Full Course
☞ https://morioh.com/p/f9ff3b5d2a00?f=5c21fb01c16e2556b555ab32

 

Variable de Impresión de Python

Python es un lenguaje versátil y flexible; a menudo hay más de una forma de lograr algo.

En este tutorial, verá algunas de las formas en que puede imprimir una cadena y una variable juntas.

¡Empecemos!

Cómo usar la print()función en Python

Para imprimir cualquier cosa en Python, se utiliza la print()función - que es la printpalabra clave seguida de un conjunto de apertura y cierre de paréntesis, ().

#how to print a string
print("Hello world")

#how to print an integer
print(7)

#how to print a variable 
#to just print the variable on its own include only the name of it

fave_language = "Python"
print(fave_language)

#output

#Hello world
#7
#Python

Si omite los paréntesis, obtendrá un error:

print "hello world"

#output after running the code:
#File "/Users/dionysialemonaki/python_articles/demo.py", line 1
#    print "hello world"
#    ^^^^^^^^^^^^^^^^^^^
#SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?

Si escribe su código Python en Visual Studio Code, con la extensión Python , también obtendrá un subrayado y una pista que indican que algo no está del todo bien:

Captura de pantalla-2021-12-07-a-3.08.14-PM

Como se mencionó anteriormente, la declaración de impresión se utiliza para generar todo tipo de información. Esto incluye datos textuales y numéricos, variables y otros tipos de datos.

También puede imprimir texto (o cadenas) combinado con variables, todo en una declaración.

Verá algunas de las diferentes formas de hacer esto en las secciones siguientes.

Cómo imprimir una variable y una cadena en Python usando la concatenación

Concatenar, según el diccionario, significa enlazar (cosas) juntas en una cadena o serie.

Esto se hace mediante la adición de varias cosas (en este caso la programación - se añaden datos), junto con otros, utilizando el operador de suma Python, +.

Tenga en cuenta que la concatenación solo se usa para cadenas, por lo que si la variable que desea concatenar con el resto de las cadenas es de un tipo de datos entero, tendrá que convertirla en una cadena con la str()función.

En el siguiente ejemplo, quiero imprimir el valor de una variable junto con algún otro texto.

Agrego las cadenas entre comillas dobles y el nombre de la variable sin rodearlo, usando el operador de suma para encadenarlos todos juntos:

fave_language = "Python"

print("I like coding in " + fave_language + " the most")

#output
#I like coding in Python the most

Con la concatenación de cadenas, debe agregar espacios usted mismo, por lo que si en el ejemplo anterior no hubiera incluido ningún espacio entre las comillas, la salida se vería así:

fave_language = "Python"

print("I like coding in" + fave_language + "the most")

#output
#I like coding inPythonthe most

Incluso puede agregar los espacios por separado:

fave_language = "Python"

print("I like coding in" + " " + fave_language + " "  + "the most")

#output
#I like coding in Python the most

Esta no es la forma más preferida de imprimir cadenas y variables, ya que puede ser propensa a errores y consumir mucho tiempo.

Cómo imprimir una variable y una cadena en Python separando cada una con una coma

Puede imprimir texto junto a una variable, separados por comas, en una declaración de impresión.

first_name = "John"

print("Hello",first_name)

#output
#Hello John

En el ejemplo anterior, primero incluí un texto que quería imprimir entre comillas dobles; en este caso, el texto era la cadena Hello.

Después de las comillas de cierre, agregué una coma que separa ese fragmento de texto del valor contenido en el nombre de la variable ( first_nameen este caso) que luego incluí.

Podría haber agregado más texto siguiendo la variable, así:

first_name = "John"

print("Hello",first_name,"good to see you")

#output
#Hello John good to see you

Este método también funciona con más de una variable:

first_name = "John"
last_name = "Doe"

print("Hello",first_name,last_name,"good to see you")

#output
Hello John Doe good to see you

Asegúrate de separar todo con una coma.

Entonces, separa el texto de las variables con una coma, pero también las variables de otras variables, como se muestra arriba.

Si no se hubiera agregado la coma entre first_namey last_name, el código habría arrojado un error:

first_name = "John"
last_name = "Doe"

print("Hello",first_name last_name,"good to see you")

#output
#File "/Users/dionysialemonaki/python_articles/demo.py", line 4
#    print("Hello",first_name last_name,"good to see you")
#                 ^^^^^^^^^^^^^^^^^^^^
#SyntaxError: invalid syntax. Perhaps you forgot a comma?

Como puede ver, los mensajes de error de Python son extremadamente útiles y facilitan un poco el proceso de depuración :)

Cómo imprimir una variable y una cadena en Python usando formato de cadena

Utiliza el formato de cadena al incluir un conjunto de llaves de apertura y cierre {}, en el lugar donde desea agregar el valor de una variable.

first_name = "John"

print("Hello {}, hope you're well!")

En este ejemplo hay una variable, first_name.

Dentro de la declaración impresa hay un conjunto de comillas dobles de apertura y cierre con el texto que debe imprimirse.

Dentro de eso, agregué un conjunto de llaves en el lugar donde quiero agregar el valor de la variable first_name.

Si intento ejecutar este código, tendrá el siguiente resultado:

#output
#Hello {}, hope you're well!

¡En realidad, no imprime el valor de first_name!

Para imprimirlo, necesito agregar el .format()método de cadena al final de la cadena, que es inmediatamente después de las comillas de cierre:

first_name = "John"

print("Hello {}, hope you're well!".format(first_name))

#output
#Hello John, hope you're well!

Cuando hay más de una variable, usa tantas llaves como la cantidad de variables que desee imprimir:

first_name = "John"
last_name = "Doe"

print("Hello {} {}, hope you're well!")

En este ejemplo, he creado dos variables y quiero imprimir ambas, una después de la otra, así que agregué dos juegos de llaves en el lugar donde quiero que se sustituyan las variables.

Ahora, cuando se trata del .format()método, importa el orden en el que coloque los nombres de las variables.

Entonces, el valor del nombre de la variable que se agregará primero en el método estará en el lugar de la primera llave, el valor del nombre de la variable que se agregará en segundo lugar estará en el lugar de la segunda llave, y pronto.

Asegúrese de separar los nombres de las variables con comas dentro del método:

first_name = "John"
last_name = "Doe"

print("Hello {} {}, hope you're well!".format(first_name,last_name))

#output
#Hello John Doe, hope you're well!

Si hubiera invertido el orden de los nombres dentro del método, la salida se vería diferente:

first_name = "John"
last_name = "Doe"

print("Hello {} {}, hope you're well!".format(last_name,first_name))

#output
#Hello Doe John, hope you're well!

Cómo imprimir una variable y una cadena en Python usando f-strings

f-strings son una forma mejor, más legible y concisa de lograr el formato de cadena en comparación con el método que vimos en la sección anterior.

La sintaxis es más sencilla y requiere menos trabajo manual.

La sintaxis general para crear un se f-stringve así:

print(f"I want this text printed to the console!")

#output
#I want this text printed to the console!

Primero incluye el carácter fantes de las comillas de apertura y cierre, dentro de la print()función.

Para imprimir una variable con una cadena en una línea, vuelva a incluir el carácter fen el mismo lugar, justo antes de las comillas.

Luego agrega el texto que desea dentro de las comillas, y en el lugar donde desea agregar el valor de una variable, agrega un conjunto de llaves con el nombre de la variable dentro de ellas:

first_name = "John"

print(f"Hello, {first_name}!")

#output
#Hello, John!

Para imprimir más de una variable, agrega otro conjunto de llaves con el nombre de la segunda variable:

first_name = "John"
last_name = "Doe"

print(f"Hello, {first_name} {last_name}!")

#output
#Hello, John Doe!

El orden en que coloque los nombres de las variables es importante, así que asegúrese de agregarlos de acuerdo con la salida que desee.

Si hubiera invertido el orden de los nombres, obtendría el siguiente resultado:

first_name = "John"
last_name = "Doe"

print(f"Hello, {last_name} {first_name}!")

#output
#Hello, Doe John!

Conclusión

¡Gracias por leer y llegar hasta el final! Ahora conoce algunas formas diferentes de imprimir cadenas y variables juntas en una línea en Python.

Si desea obtener más información sobre Python, consulte la Certificación Python de freeCodeCamp .

Es adecuado para principiantes, ya que comienza desde los fundamentos y se construye gradualmente hacia conceptos más avanzados. También podrás construir cinco proyectos y poner en práctica todos los nuevos conocimientos que adquieras.

¡Feliz codificación!

https://www.freecodecamp.org/news/python-print-variable-how-to-print-a-string-and-variable/

#python 

Cómo Recortar Una Cadena En Python Usando El Método .strip()

En este artículo, aprenderá cómo recortar una cadena en Python usando el .strip()método.

También verá cómo usar los métodos .lstrip()y .rstrip(), que son las contrapartes de .strip().

¡Empecemos!

Cómo recortar una cadena en Python

Python tiene tres métodos incorporados para recortar los espacios en blanco iniciales y finales y los caracteres de las cadenas.

  • .strip()
  • .lstrip()
  • .rstrip()

Cada método devuelve una nueva cadena recortada.

Cómo eliminar los espacios en blanco iniciales y finales de las cadenas en Python

Cuando el .strip()método no tiene argumentos, elimina cualquier espacio en blanco inicial o final de una cadena.

Por lo tanto, si tiene un espacio en blanco al principio y/o al final de una palabra o frase, .strip()solo, de forma predeterminada, lo eliminará.

La siguiente variable greetingtiene almacenada la cadena "Hola". La cadena tiene espacio tanto a la derecha como a la izquierda.

greeting = "     Hello!  "

print(greeting,"How are you?")

#output
#     Hello!   How are you?

Para eliminar ambos, utiliza el .strip()método, así:

greeting = "     Hello!  "

stripped_greeting = greeting.strip()

print(stripped_greeting,"How are you?")

#output
#Hello! How are you?

También podrías haber usado el .strip()método de esta manera:

greeting = "     Hello!  "

print(greeting.strip(),"How are you?")

#output
#Hello! How are you?

Cómo eliminar caracteres iniciales y finales de cadenas en Python

El .strip()método toma caracteres opcionales pasados ​​como argumentos.

Los caracteres que agrega como argumentos especifican qué caracteres desea eliminar del principio y el final de la cadena.

A continuación se muestra la sintaxis general para este caso:

str.strip(char)

Los caracteres que especifique se encierran entre comillas.

Entonces, por ejemplo, supongamos que tiene la siguiente cadena:

greeting = "Hello World?"

Desea eliminar "H" y "?", que están al principio y al final de la cadena, respectivamente.

Para eliminarlos, pasa ambos caracteres como argumentos a strip().

greeting = "Hello World?"

stripped_greeting = greeting.strip("H?")

print(stripped_greeting)

#output
#ello World

Observe lo que sucede cuando desea eliminar "W" de "World", que está en el medio y no al principio o al final de la cadena, y lo incluye como argumento:

greeting = "Hello World?"

stripped_greeting = greeting.strip("HW?")

print(stripped_greeting)
#ello World

¡No se eliminará! Solo se eliminan los caracteres al principio y al final de dicha cadena.

Dicho esto, mira el siguiente ejemplo.

Digamos que desea eliminar los dos primeros y los dos últimos caracteres de la cadena:

phrase = "Hello world?"

stripped_phrase = phrase.strip("Hed?")

print(stripped_phrase)

#output
#llo worl

Se han eliminado los dos primeros caracteres ("Él") y los dos últimos ("d?") de la cadena.

Otra cosa a tener en cuenta es que el argumento no elimina solo la primera instancia del carácter especificado.

Por ejemplo, supongamos que tiene una cadena con algunos puntos al principio y algunos signos de exclamación al final:

phrase = ".....Python !!!"

Cuando especifica como argumentos .y !, se eliminarán todas las instancias de ambos:

phrase = ".....Python !!!"

stripped_phrase = phrase.strip(".!")

print(stripped_phrase)

#output
#Python 

Cómo eliminar solo los espacios en blanco y los caracteres iniciales de las cadenas en Python

Para eliminar solo los espacios en blanco y los caracteres iniciales, use .lstrip().

Esto es útil cuando desea eliminar espacios en blanco y caracteres solo desde el comienzo de la cadena.

Un ejemplo de esto sería eliminar el www.de un nombre de dominio.

domain_name = "www.freecodecamp.org www."

stripped_domain = domain_name.lstrip("w.")

print(stripped_domain)

#output
#freecodecamp.org www.

En este ejemplo, utilicé los caracteres wy .tanto al principio como al final de la cadena para mostrar cómo .lstrip()funciona.

Si lo hubiera usado .strip(w.), tendría el siguiente resultado:

freecodecamp.org 

Lo mismo ocurre con la eliminación de espacios en blanco.

Tomemos un ejemplo de una sección anterior:

greeting = "     Hello!  "

stripped_greeting = greeting.lstrip()

print(stripped_greeting,"How are you?" )

#output
#Hello!   How are you?

Solo el espacio en blanco del comienzo de la cadena se ha eliminado de la salida.

Cómo eliminar solo los espacios en blanco finales y los caracteres de las cadenas en Python

Para eliminar solo los espacios en blanco y los caracteres finales, utilice el .rstrip()método.

Digamos que desea eliminar todos los signos de puntuación solo del final de una cadena.

Harías lo siguiente:

enthusiastic_greeting = "!!! Hello !!!!"

less_enthusiastic_greeting = enthusiastic_greeting.rstrip("!")

print(less_enthusiastic_greeting)

#output
#!!! Hello 

Lo mismo ocurre con los espacios en blanco.

Tomando nuevamente el ejemplo anterior, esta vez el espacio en blanco se eliminaría solo al final de la salida:

greeting = "     Hello!  "

stripped_greeting = greeting.rstrip()

print(stripped_greeting,"How are you?")

#output
#     Hello! How are you?

Conclusión

¡Y ahí lo tienes! Ahora conoce los conceptos básicos de cómo recortar una cadena en Python.

Para resumir:

  • Utilice el .strip()método para eliminar los espacios en blanco y los caracteres del principio y el final de una cadena.
  • Use el .lstrip()método para eliminar espacios en blanco y caracteres solo desde el principio de una cadena.
  • Use el .rstrip()método para eliminar espacios en blanco y caracteres solo del final de una cadena.


Enlace: https://www.freecodecamp.org/news/python-strip-how-to-trim-a-string-or-line/

#python 

how to trim a string in Python using the .strip() method

In this article, you'll learn how to trim a string in Python using the .strip() method.

You'll also see how to use the .lstrip() and .rstrip() methods, which are the counterparts to .strip().

Let's get started!

How to trim a string in Python

Python has three built-in methods for trimming leading and trailing whitespace and characters from strings.

  • .strip()
  • .lstrip()
  • .rstrip()

Each method returns a new trimmed string.

How to Remove Leading and Trailing Whitespace from Strings in Python

When the .strip() method has no argument, it removes any leading and/or trailing whitespace from a string.

So, if you have whitespace at the start and/or end of a word or phrase, .strip() alone, by default, will remove it.

The following variable greeting has the string "Hello" stored in it. The string has space both to the right and left of it.

greeting = "     Hello!  "

print(greeting,"How are you?")

#output
#     Hello!   How are you?

To remove both of them, you use the .strip() method, like so:

greeting = "     Hello!  "

stripped_greeting = greeting.strip()

print(stripped_greeting,"How are you?")

#output
#Hello! How are you?

You could have also used the .strip() method in this way:

greeting = "     Hello!  "

print(greeting.strip(),"How are you?")

#output
#Hello! How are you?

How to Remove Leading and Trailing Characters from Strings in Python

The .strip() method takes optional characters passed as arguments.

The characters you add as arguments specify what characters you would like to remove from the start and end of the string.

Below is the general syntax for this case:

str.strip(char)

The characters you specify are enclosed in quotation marks.

So, for example, say you have the following string:

greeting = "Hello World?"

You want to remove "H" and "?", which are at the beginning and at end of the string, respectively.

To remove them, you pass both characters as arguments to strip().

greeting = "Hello World?"

stripped_greeting = greeting.strip("H?")

print(stripped_greeting)

#output
#ello World

Notice what happens when you want to remove "W" from "World", which is at the middle and not at the start or end of the string, and you include it as an argument:

greeting = "Hello World?"

stripped_greeting = greeting.strip("HW?")

print(stripped_greeting)
#ello World

It will not be removed! Only the characters at the start and end of said string get deleted.

That being said, look at the next example.

Say you want to remove the first two and the last two characters of the string:

phrase = "Hello world?"

stripped_phrase = phrase.strip("Hed?")

print(stripped_phrase)

#output
#llo worl

The first two characters ("He") and the last two ("d?") of the string have been removed.

Another thing to note is that the argument does not remove only the first instance of the character specified.

For example, say you have a string with a few periods at the beginning and a few exclamation marks at the end:

phrase = ".....Python !!!"

When you specify as arguments . and !, all instances of both will get removed:

phrase = ".....Python !!!"

stripped_phrase = phrase.strip(".!")

print(stripped_phrase)

#output
#Python 

How to Remove Only Leading Whitespace and Characters from Strings in Python

To remove only leading whitespace and characters, use .lstrip().

This is helpful when you want to remove whitespace and characters only from the start of the string.

An example for this would be removing the www. from a domain name.

domain_name = "www.freecodecamp.org www."

stripped_domain = domain_name.lstrip("w.")

print(stripped_domain)

#output
#freecodecamp.org www.

In this example I used the w and . characters both at the start and the end of the string to showcase how .lstrip() works.

If I'd used .strip(w.) I'd have the following output:

freecodecamp.org 

The same goes for removing whitespace.

Let's take an example from a previous section:

greeting = "     Hello!  "

stripped_greeting = greeting.lstrip()

print(stripped_greeting,"How are you?" )

#output
#Hello!   How are you?

Only the whitespace from the start of the string has been removed from the output.

How to Remove only Trailing Whitespace and Characters from Strings in Python

To remove only trailing whitespace and characters, use the .rstrip() method.

Say you wanted to remove all punctuation only from the end of a string.

You would do the following:

enthusiastic_greeting = "!!! Hello !!!!"

less_enthusiastic_greeting = enthusiastic_greeting.rstrip("!")

print(less_enthusiastic_greeting)

#output
#!!! Hello 

Same goes for whitespace.

Taking again the example from earlier, this time the whitespace would be removed only from the end of the output:

greeting = "     Hello!  "

stripped_greeting = greeting.rstrip()

print(stripped_greeting,"How are you?")

#output
#     Hello! How are you?

Conclusion

And there you have it! You now know the basics of how to trim a string in Python.

To sum up:

  • Use the .strip() method to remove whitespace and characters from the beginning and the end of a string.
  • Use the .lstrip() method to remove whitespace and characters only from the beginning of a string.
  • Use the .rstrip() method to remove whitespace and characters only from the end of a string.


Link: https://www.freecodecamp.org/news/python-strip-how-to-trim-a-string-or-line/

#python 

山岸  英樹

山岸 英樹

1642085762

.strip()メソッドを使用してPythonで文字列をトリミングする

この記事では、.strip()メソッドを使用してPythonで文字列をトリミングする方法を学習します。

また、に対応するメソッド.lstrip().rstrip()メソッドの使用方法もわかります.strip()

始めましょう!

Pythonで文字列をトリミングする方法

Pythonには、文字列から先頭と末尾の空白と文字をトリミングするための3つの組み込みメソッドがあります。

  • .strip()
  • .lstrip()
  • .rstrip()

各メソッドは、新しいトリミングされた文字列を返します。

Pythonで文字列から先頭と末尾の空白を削除する方法

とき.strip()メソッドは、引数を持っていない、それは文字列から、先頭および/または末尾の空白を削除します。

したがって、単語やフレーズの先頭や末尾に空白がある場合.strip()は、デフォルトで単独で削除されます。

次の変数にgreetingは、文字列「Hello」が格納されています。文字列の左右両方にスペースがあります。

greeting = "     Hello!  "

print(greeting,"How are you?")

#output
#     Hello!   How are you?

それらの両方を削除するには.strip()、次のような方法を使用します。

greeting = "     Hello!  "

stripped_greeting = greeting.strip()

print(stripped_greeting,"How are you?")

#output
#Hello! How are you?

.strip()この方法を次のように使用することもできます。

greeting = "     Hello!  "

print(greeting.strip(),"How are you?")

#output
#Hello! How are you?

Pythonで文字列から先頭と末尾の文字を削除する方法

この.strip()メソッドは、引数として渡されたオプションの文字を受け取ります

引数として追加する文字は、文字列の最初と最後から削除する文字を指定します。

この場合の一般的な構文は次のとおりです。

str.strip(char)

指定する文字は引用符で囲みます。

したがって、たとえば、次の文字列があるとします。

greeting = "Hello World?"

文字列の最初と最後にある「H」と「?」をそれぞれ削除します。

それらを削除するには、両方の文字を引数としてに渡しますstrip()

greeting = "Hello World?"

stripped_greeting = greeting.strip("H?")

print(stripped_greeting)

#output
#ello World

文字列の先頭または末尾ではなく中央にある「World」から「W」を削除し、引数として含めるとどうなるかに注意してください。

greeting = "Hello World?"

stripped_greeting = greeting.strip("HW?")

print(stripped_greeting)
#ello World

削除されません!で、文字だけの開始終了と文字列のは削除されます。

そうは言っても、次の例を見てください。

文字列の最初の2文字と最後の2文字を削除するとします。

phrase = "Hello world?"

stripped_phrase = phrase.strip("Hed?")

print(stripped_phrase)

#output
#llo worl

文字列の最初の2文字( "He")と最後の2文字( "d?")は削除されました。

もう1つの注意点は、引数が指定された文字の最初のインスタンスだけを削除するわけではないということです。

たとえば、最初にいくつかのピリオドがあり、最後にいくつかの感嘆符がある文字列があるとします。

phrase = ".....Python !!!"

引数として.とを指定すると!、両方のすべてのインスタンスが削除されます。

phrase = ".....Python !!!"

stripped_phrase = phrase.strip(".!")

print(stripped_phrase)

#output
#Python 

Pythonで文字列から先頭の空白と文字のみを削除する方法

先頭の空白と文字のみを削除するに、を使用します.lstrip()

これは、文字列の先頭からのみ空白と文字を削除する場合に役立ちます。

この例としてwww.、ドメイン名からを削除する場合があります。

domain_name = "www.freecodecamp.org www."

stripped_domain = domain_name.lstrip("w.")

print(stripped_domain)

#output
#freecodecamp.org www.

この例では、文字列の最初と最後の両方でw.文字を使用して、どのように.lstrip()機能するかを示しました。

使用した場合.strip(w.)、次の出力が得られます。

freecodecamp.org 

空白の削除についても同じことが言えます。

前のセクションの例を見てみましょう。

greeting = "     Hello!  "

stripped_greeting = greeting.lstrip()

print(stripped_greeting,"How are you?" )

#output
#Hello!   How are you?

文字列の先頭からの空白のみが出力から削除されています。

Pythonで文字列から末尾の空白と文字のみを削除する方法

末尾の空白と文字のみを削除するには、この.rstrip()メソッドを使用します。

文字列の末尾からのみすべての句読点を削除したいとします。

次のようにします。

enthusiastic_greeting = "!!! Hello !!!!"

less_enthusiastic_greeting = enthusiastic_greeting.rstrip("!")

print(less_enthusiastic_greeting)

#output
#!!! Hello 

空白についても同じことが言えます。

前の例をもう一度取り上げると、今回は出力の最後からのみ空白が削除されます。

greeting = "     Hello!  "

stripped_greeting = greeting.rstrip()

print(stripped_greeting,"How are you?")

#output
#     Hello! How are you?

結論

そして、あなたはそれを持っています!これで、Pythonで文字列をトリミングする方法の基本を理解できました。

総括する:

  • この.strip()メソッドを使用して、文字列の最初最後から空白と文字を削除します。
  • この.lstrip()メソッドを使用して、文字列の先頭からのみ空白と文字を削除します。
  • この.rstrip()メソッドを使用して、文字列の末尾からのみ空白と文字を削除します。


リンク:https//www.freecodecamp.org/news/python-strip-how-to-trim-a-string-or-line/

#python 

Android Hello World Program - Create Your First App in Android Studio

Android Hello World example in Android Studio – In this tutorial, we’ll show you how to start android development with the very first android project.

As a beginner first of all you must develop the hello world application like we do while learning a new language. This project doesn’t involve any business logic rather it ensures whether our development, as well as the deployment environment, is working. This is indeed a very simple android project and you do not really need to do a lot of coding here.

#android tutorials #android hello world #android project #android studio hello world #first android app #hello world program in android