A veces, mientras trabajamos con Python Strings, tenemos un problema en el que necesitamos realizar el reemplazo de puntuaciones en String con un carácter específico. Esto puede tener aplicación en muchos dominios, como la programación día a día. Analicemos ciertas formas en que se puede realizar esta tarea.
Método #1: Usarstring.punctuation + replace()
La combinación de las funciones anteriores se puede usar para resolver este problema. En esto, extraemos todos los signos de puntuación usando puntuación y realizamos un reemplazo del carácter deseado usando replace().
# Python3 code to demonstrate working of # Replace punctuations with K # Using string.punctuation + replace() from string import punctuation # initializing string test_str = 'geeksforgeeks, is : best for ; geeks !!' # printing original string print("The original string is : " + str(test_str)) # initializing replace character repl_char = '*' # Replace punctuations with K # Using string.punctuation + replace() for chr in punctuation: test_str = test_str.replace(chr, repl_char) # printing result print("The strings after replacement : " + test_str)
The original string is : geeksforgeeks, is : best for ; geeks!! The strings after replacement : geeksforgeeks* is * best for * geeks**
Método #2: Usando regex
Este problema se puede resolver usando regex. En esto, empleamos una expresión regular para sustituir todos los signos de puntuación.
# Python3 code to demonstrate working of # Replace punctuations with K # Using regex import re # initializing string test_str = 'geeksforgeeks, is : best for ; geeks !!' # printing original string print("The original string is : " + str(test_str)) # initializing replace character repl_char = '*' # Replace punctuations with K # Using regex res = re.sub(r'[^\w\s]', repl_char, test_str) # printing result print("The strings after replacement : " + res)
The original string is : geeksforgeeks, is : best for ; geeks!! The strings after replacement : geeksforgeeks* is * best for * geeks**
Publicación traducida automáticamente
Artículo escrito por manjeet_04 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA