简体   繁体   English

如何从列表中的字符串中删除字符?

[英]How do I remove a character from strings in a list?

I am working with a module called PyDictionary . 我正在使用一个名为PyDictionary的模块。 Whenever it gets the synonym of a word, it creates a list of the synonyms, however when I try print the list , it has a 'u' before the synonym, example: 每当它得到一个单词的同义词时,它都会创建一个同义词list ,但是当我尝试printlist ,它在同义词之前有一个'u' ,例如:

[u'welcome', u'howdy', u'hi', u'greetings', u'bonjour']

I've tried: synonym = re.sub('u','',synonym[0]) , and this works, but only prints 'welcome' , not the entire list . 我试过了: synonym = re.sub('u','',synonym[0]) ,这可行,但是只打印'welcome' ,而不是整个list

Any help would be greatly appreciated. 任何帮助将不胜感激。 Thanks! 谢谢!

如果要将list转换为strings list ,可以使用list推导,例如:

result = [str(x) for x in synonym]

The u you are seeing is not part of the string content, and therefore cannot be removed with regular expression substitution. 您看到的u不属于字符串内容,因此无法使用正则表达式替换将其删除。 Instead, it should be considered part of the opening quote . 相反,应将其视为开头报价的一部分 The syntax of the Python language itself allows for string literals to be defined with quotes that are inflected in this way. Python语言本身的语法允许使用以这种方式引起变化的引号定义字符串文字。 For example: 例如:

a = 'spam'
b = u'spam'   # in Python 2, a and b are different types

When you display the variable the way you would to a programmer , ie in such a way that the quote characters are visible (eg just typing synonym[0] at the prompt, or trying to print the whole list synonym , or otherwise invoking Python's repr() mechanism on the strings) then the u will be visible too. 当您以向程序员的方式显示变量时,即以引号字符可见的方式显示(例如,在提示符下键入synonym[0] ,或尝试print整个列表synonym ,或以其他方式调用Python的repr()字符串的机制),那么u也将可见。 By contrast, when you display the variable as you would to a user (eg with print synonym[0] , or by join ing the list and then print ing the resulting string) then, just as you would not expect to see the quote characters themselves, you will also not see the u . 相反,当您像对用户一样显示变量时(例如,使用print synonym[0]或通过join列表然后print结果字符串),就像您不会看到引号一样自己,您也不会看到u

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM