Ir al contenido
Odoo Menú
  • Identificarse
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • TPV para tiendas
    • TPV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en directo
    • e-learning
    Cadena de suministro
    • Inventario
    • Fabricación
    • PLM
    • Compra
    • Mantenimiento
    • Calidad
    Recursos Humanos
    • Empleados
    • Reclutamiento
    • Ausencias
    • Evaluación
    • Referencias
    • Flota
    Marketing
    • Marketing social
    • Marketing por correo electrónico
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyecto
    • Partes de horas
    • Servicio de campo
    • Servicio de asistencia
    • Planificación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Conocimientos
    • WhatsApp
    Aplicaciones de terceros Studio de Odoo Plataforma de Odoo Cloud
  • Industrias
    Comercio al por menor
    • Librería
    • Tienda de ropa
    • Tienda de muebles
    • Tienda de ultramarinos
    • Ferretería
    • Juguetería
    Alimentación y hostelería
    • Bar y pub
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidor de bebidas
    • Hotel
    Inmueble
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión inmobiliaria
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Empresa contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Fabricación
    • Textil
    • Metal
    • Muebles
    • Alimentos
    • Cervecería
    • Regalos de empresas
    Salud y bienestar
    • Club deportivo
    • Óptica
    • Gimnasio
    • Terapeutas
    • Farmacia
    • Peluquería
    Oficios
    • Handyman
    • Hardware y soporte técnico
    • Sistemas de energía solar
    • Zapatero
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin ánimo de lucro
    • Agencia de protección del medio ambiente
    • Alquiler de paneles publicitarios
    • Estudio fotográfico
    • Alquiler de bicicletas
    • Distribuidor de software
    Explorar todos los sectores
  • Comunidad
    Aprender
    • Tutoriales
    • Documentación
    • Certificaciones
    • Formación
    • Blog
    • Podcast
    Potenciar la educación
    • Programa de formación
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtener el software
    • Descargar
    • Comparar ediciones
    • Versiones
    Colaborar
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Convertirse en partner
    • Servicios para partners
    • Registrar tu empresa contable
    Obtener servicios
    • Encontrar un partner
    • Encontrar un asesor fiscal
    • Contacta con un experto
    • Servicios de implementación
    • Referencias de clientes
    • Ayuda
    • Actualizaciones
    GitHub YouTube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicitar una demostración
  • Precios
  • Ayuda

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Contabilidad
  • Inventario
  • PoS
  • Proyecto
  • MRP
All apps
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Ayuda

How can i remove unwanted characters from string ?

Suscribirse

Reciba una notificación cuando haya actividad en esta publicación

Se marcó esta pregunta
5 Respuestas
22335 Vistas
Avatar
Dr Obx

Already tried using: name = str.replace(name, ",","") but either i don't know what should I import into module or should i use different command

or getting an error: TypeError: descriptor 'replace' requires a 'str' object but received a 'list'

Would anyone tell me how  to do it ?

Quiet urgent ..... ;)

 

1
Avatar
Descartar
Hiral Patel (hip)

Try this code: name = [i.replace(",", "") for i in name]

Dr Obx
Autor
numbers = self.eangen()
numbers.append(self.calcheck(numbers))
res = ''.join(map(str, numbers))
record.write({'intcode': res})
Puzzle solved (partially) :)
Avatar
Anil Kesariya
Mejor respuesta

Hi Dr Obx,

You can use strip() or replace() method.

str = " Anil Kesariya "
new_str = str.strip()
# o/p: Anil Kesariya

This method will remove unwanted space from left and right side of string.

If you want to remove the space or any symbolic pattern from whole string than you can use replace().

eg:1 remove space
str = " A n i l K e s a r i y a "
new_str = str.strip(" ","")
o/p : Anilkesariya
eg:2 remove "
str = Anil"kesari"ya'
new_str = str.replace('"',"")
o/p: Anilkesariya

Hope this will help.

Rgds,

Anil.






1
Avatar
Descartar
Avatar
Rihene
Mejor respuesta

Hello my friend;

Strings in python are immutable (can't be changed). Because of this, the effect of line.replace(...) is just to create a new string, rather than changing the old one. You need to rebind (assign) it to line in order to have that variable take the new value, with those characters removed.

Also, the way you are doing it is going to be kind of slow, relatively. It's also likely to be a bit confusing to experienced pythonators, who will see a doubly-nested structure and think for a moment that something more complicated is going on.

You can instead use str.translate: (https://docs.python.org/2/library/stdtypes.html#str.translate)

line = line.translate(None, '!@#$')

which only works on Python 2.6 and newer Python 2.x versions * —

or regular expression replacement with re.sub (https://docs.python.org/2/library/re.html#re.sub)

import re

line = re.sub('[!@#$]', '', line)

Here is an example:

s = "this is a string"

l = list(s) # convert to list

l[1] = "" # "delete" letter h (the item actually still exists but is empty)

l[1:2] = [] # really delete letter h (the item is actually removed from the list)

del(l[1]) # another way to delete it

p = l.index("a") # find position of the letter "a"

del(l[p]) # delete it

s = "".join(l) # convert back to string

Timing comparison

def findreplace(m_string, char):

m_string = list(m_string)

for k in m_string:

if k == char:

del(m_string[m_string.index(k)])

return "".join(m_string)

def replace(m_string, char):

return m_string.replace("i", "")

def translate(m_string, char):

return m_string.translate(None, "i")

from timeit import timeit

print timeit("findreplace('it is icy','i')", "from __main__ import findreplace")

print timeit("replace('it is icy','i')", "from __main__ import replace")

print timeit("translate('it is icy','i')", "from __main__ import translate")

Result

1.64474582672
0.29278588295
0.311302900314

str.replace and str.translate methods are 8 and 5 times faster.

Regards.

0
Avatar
Descartar
Dr Obx
Autor

Gr8 thanx. I'm a beginner so every information matter ;) I'll take it into my head so next time I'll try your ideas and methods ;) Thank you

¿Le interesa esta conversación? ¡Participe en ella!

Cree una cuenta para poder utilizar funciones exclusivas e interactuar con la comunidad.

Inscribirse
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento Odoo.sh
  • Ayuda
  • Actualizar
  • Desarrollos personalizados
  • Educación
  • Encontrar un asesor fiscal
  • Encontrar un partner
  • Convertirse en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contacta con nosotros
  • Puestos de trabajo
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Información legal • Privacidad
  • Seguridad
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo es un conjunto de aplicaciones de código abierto que cubren todas las necesidades de tu empresa: CRM, comercio electrónico, contabilidad, inventario, punto de venta, gestión de proyectos, etc.

La propuesta única de valor de Odoo es ser muy fácil de usar y totalmente integrado.

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now