![](/img/trans.png)
[英]Python/Django: How to remove extra white spaces & tabs from a string?
[英]Remove spaces and tabs within a string in python
如何在 python 中刪除字符串中的特定空格。
我的輸入字符串是:,
str1 = """vendor_id\t: GenuineIntel
cpu family\t: 6
model\t\t: 58
model name\t: Intel(R) Core(TM) i3-3120M CPU @ 2.50GHz
stepping\t: 9
cpu MHz\t\t: 2485.659
cache size\t: 6144 KB
fpu\t\t: yes
fpu_exception\t: yes
cpuid level\t: 5
wp\t\t: yes"""
我需要的輸出是:
>>>print str1
vendor_id: GenuineIntel
cpu family: 6
model: 58
model name: Intel(R) Core(TM) i3-3120M CPU @ 2.50GHz
stepping: 9
cpu MHz: 2485.659
cache size: 6144 KB
fpu: yes
fpu_exception: yes
cpuid level: 5
wp: yes
看起來您想從行首刪除空格,並刪除冒號前的所有空格。 使用正則表達式:
import re
re.sub(r'(^[ \t]+|[ \t]+(?=:))', '', str1, flags=re.M)
這會在行首( ^[ \\t]*
, ^
是行的開頭, [ \\t]
是空格或制表符, +
是 1 或更多),或者選擇空格和制表符冒號前的制表符( [ \\t]+
是 1 個或多個空格和制表符, (?=:)
表示:
字符必須跟在后面但不包含在所選擇的內容中),然后將這些空格和制表符替換為空字符串。 flags=re.M
是為了確保模式在每一行上都有效。
演示:
>>> import re
>>> str1 = """vendor_id\t: GenuineIntel
... cpu family\t: 6
... model\t\t: 58
... model name\t: Intel(R) Core(TM) i3-3120M CPU @ 2.50GHz
... stepping\t: 9
... cpu MHz\t\t: 2485.659
... cache size\t: 6144 KB
... fpu\t\t: yes
... fpu_exception\t: yes
... cpuid level\t: 5
... wp\t\t: yes"""
>>> print re.sub(r'(^[ \t]+|[ \t]+(?=:))', '', str1, flags=re.M)
vendor_id: GenuineIntel
cpu family: 6
model: 58
model name: Intel(R) Core(TM) i3-3120M CPU @ 2.50GHz
stepping: 9
cpu MHz: 2485.659
cache size: 6144 KB
fpu: yes
fpu_exception: yes
cpuid level: 5
wp: yes
如果輸入的字符串沒有前導空格(和你只是你自己縮進你的樣品,使它看起來一字排開),那么所有要刪除的選項卡:
str1 = str1.replace('\t', '')
並完成它。
我不知道你所說的“隨機”是什么意思,但你可以刪除所有標簽:
str1 = str1.replace("\t", "")
這將解決您的答案:
str1 = """vendor_id\t: GenuineIntel
cpu family\t: 6
model\t\t: 58
model name\t: Intel(R) Core(TM) i3-3120M CPU @ 2.50GHz
stepping\t: 9
cpu MHz\t\t: 2485.659
cache size\t: 6144 KB
fpu\t\t: yes
fpu_exception\t: yes
cpuid level\t: 5
wp\t\t: yes"""
arr = [line.strip() for line in str1.split('\n')]
for line in arr:
print line.strip()
def invitation_ics():
text = f"""BEGIN:VCALENDAR
CLASS:PUBLIC
STATUS:CONFIRMED
"""
retunr text
出不是標簽
BEGIN:VCALENDAR
CLASS:PUBLIC
STATUS:CONFIRMED
str1 = str1.replace("\t", "").replace(" ", "")
它會先替換制表符,然后替換空格。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.