簡體   English   中英

如何在 python 中將字符串轉換為蛇形格式

[英]How to convert string to snakecase format in python

我做了一個snakecase可以將每個字符串轉換為蛇形,但我的一些字符串會產生問題。 我使用re模塊

整個代碼

import re

def toSnakeCase(string, restToLower : bool = False):
  string = re.sub(r'(?:(?<=[a-z])(?=[A-Z]))|[^a-zA-Z]', ' ', self.string).replace(' ', '_')

  if (restToLower == True):
    return ''.join(self.string.lower())
  else:
    return ''.join(self.string)

輸入

strings = ['hello world', 'HelloWorld', '-HELLO-WORLD-', 'Hello-World', 'hello_world', '--hello.world', 'Hello-WORLD', 'helloWORLD']

# using enumerate just to see which list item creating problem
for i, j in enumerate(strings, 1):
  print(f'{i}. {toSnakeCaseV1(j)}')

OUTPUT - 沒有restToLower = True

1. hello_world
2. Hello_World
3. _HELLO_WORLD_
4. Hello_World
5. hello_world
6. __hello_world
7. Hello_WORLD
8. hello_WORLD

restToLower = True

1. hello_world
2. hello_world
3. _hello_world_
4. hello_world
5. hello_world
6. __hello_world
7. hello_world
8. hello_world

如您所見,第3項和第 6項造成了問題。 根據我的說法,有人知道它為什么這樣做,我的正則表達式是正確的。

預計 Output

1. hello_world
2. hello_world
3. hello_world
4. hello_world
5. hello_world
6. hello_world
7. hello_world
8. hello_world

您的問題似乎只是前導和尾隨_ ,在space > _轉換之前或之后刪除它們

def toSnakeCase(string):
    string = re.sub(r'(?<=[a-z])(?=[A-Z])|[^a-zA-Z]', ' ', string).strip().replace(' ', '_')
    return ''.join(string.lower())

用於后期剝離

string = re.sub(r'(?<=[a-z])(?=[A-Z])|[^a-zA-Z]', ' ', string).replace(' ', '_').strip("_")

你能試一下嗎:

def toSnakeCase(string):
    return re.sub(r'(?<=[a-z])(?=[A-Z])|[^a-zA-Z]', '_', string).strip('_').lower()

for i, j in enumerate(strings, 1):
    print(f'{i}. {toSnakeCase(j)}')

Output:

1. hello_world
2. hello_world
3. hello_world
4. hello_world
5. hello_world
6. hello_world
7. hello_world
8. hello_world

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM