从字符串中删除前导空格

发布于 2024-10-27 20:09:33 字数 115 浏览 9 评论 0原文

你好,我有 python 中的字符串列表

[" 0", " 1", " 2"] 

,我想删除其中一个字符串开头的空格。

我该怎么做?

Hi I have list of strings in python

[" 0", " 1", " 2"] 

and I want to remove the whitespace from the start of one of them.

How would I do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

爱冒险 2024-11-03 20:09:33

如果您想删除所有空白,您可以使用

a = [" 0", " 1", " 2"]
b = [s.lstrip() for s in a]

如果您确实只想删除其中一个,请使用

a[i] = a[i].lstrip()

其中 i 是您要删除的索引。

If you want to remove the whitespace from all of them, you could use

a = [" 0", " 1", " 2"]
b = [s.lstrip() for s in a]

If you really only want to strip one of them, use

a[i] = a[i].lstrip()

where i is the index of the one you want to strip.

屋檐 2024-11-03 20:09:33

要删除空格,您可以使用 strip 方法,然后使用位置运算符访问并分配列表中的该位置,对于位置 0 中的元素,您应该执行以下操作:

l[0] = l[0].strip()

To remove the spaces you can use the strip method, then use the positional operator to access and assign that position on the list, for the element in position 0 you should do:

l[0] = l[0].strip()
绾颜 2024-11-03 20:09:33

嘘...

li = [" 0", " 1", " 2"]
li = map(str.lstrip,li)

boooooh...

li = [" 0", " 1", " 2"]
li = map(str.lstrip,li)
兲鉂ぱ嘚淚 2024-11-03 20:09:33

如果你想从头开始删除,你可以使用lstrip()。否则,您可以使用 strip() 删除尾随和前导。

you can use lstrip() if you want to remove from start. Otherwise, you can use strip() to remove trailing and leading.

想你的星星会说话 2024-11-03 20:09:33

如果您希望结果是整数列表,那么

>>> w = [" 0", " 1" ," 2"]
>>> map(lambda a:eval(a),w)
[0, 1, 2]

如果您希望结果是字符串列表,请尝试此操作

>>> w = [" 0", " 1" ," 2"]
>>> map(lambda a:a.strip(),w)
['0', '1', '2']
>>>

If you want the the result to be a list of intergers then try this

>>> w = [" 0", " 1" ," 2"]
>>> map(lambda a:eval(a),w)
[0, 1, 2]

else if you want it to be a list of string

>>> w = [" 0", " 1" ," 2"]
>>> map(lambda a:a.strip(),w)
['0', '1', '2']
>>>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文