如何从字符串中删除连续的两个字母?
例如:
a_str = 'hii thherre'
应该成为
'hi there'
我试图做:
a_str = ''.join(sorted(set(a_str), key=a_str.index))
但是,我得到了:
'hi ter'
答案 0 :(得分:3)
是的,也可以考虑[三连或四个连续字母]
在这种情况下,如果我理解正确,那么您只想取每个连续的相等字母序列中的一个。考虑itertools.groupby
。
>>> from itertools import groupby
>>> a_str = 'hii thherre'
>>> ''.join(k for k, _ in groupby(a_str))
'hi there'
编辑:奖金正则表达式
>>> import re
>>> re.sub(r'(.)\1*', r'\1', a_str)
'hi there'
答案 1 :(得分:1)
您可以通过迭代所有字符及其下一个元素的组合并选择不相等的元素来实现此目的。
from itertools import zip_longest
a_str = 'hii thherre'
new_a = ''.join(i[0] for i in zip_longest(a_str, a_str[1:]) if i[0] != i[1])
print(new_a) # -> hi there
答案 2 :(得分:0)
没有任何输入的直接python
分割字符串并检查下一个字符是否相同,如果相同,则将其删除。
public static DataTable GetDataFromExcel(string path, dynamic worksheet)
{
//Save the uploaded Excel file.
DataTable dt = new DataTable();
//Open the Excel file using ClosedXML.
using (XLWorkbook workBook = new XLWorkbook(path))
{
//Read the first Sheet from Excel file.
IXLWorksheet workSheet = workBook.Worksheet(worksheet);
//Create a new DataTable.
//Loop through the Worksheet rows.
bool firstRow = true;
foreach (IXLRow row in workSheet.Rows())
{
//Use the first row to add columns to DataTable.
if (firstRow)
{
foreach (IXLCell cell in row.Cells())
{
if (!string.IsNullOrEmpty(cell.Value.ToString()))
{
dt.Columns.Add(cell.Value.ToString());
}
else
{
break;
}
}
firstRow = false;
}
else
{
int i = 0;
DataRow toInsert = dt.NewRow();
foreach (IXLCell cell in row.Cells(1, dt.Columns.Count))
{
try
{
toInsert[i] = cell.Value.ToString();
}
catch (Exception ex)
{
}
i++;
}
dt.Rows.Add(toInsert);
}
}
return dt;
}
答案 3 :(得分:0)
另一个纯Python版本,函数式风格:
import operator
getter = operator.itemgetter(1)
it = iter(s)
result = next(it) + ''.join(map(getter, filter(lambda x: x[0] != x[1], zip(s, it))))
或者,避免导入:
it = iter(s)
result = next(it) + ''.join(map(lambda x: x[1], filter(lambda x: x[0] != x[1], zip(s, it))))
答案 4 :(得分:0)
简单的方法,使用for循环和if-condition:
a_str = 'hii thherre'
s = a_str[0]
for i in range(1, len(a_str)):
if(a_str[i-1] != a_str[i]): s += a_str[i]
print(s) #hi there