2013-11-07 3 views
1

Я пытаюсь переместить специальный символ из одной позиции в другую в строке. Я хочу, чтобы он появился после следующего символа. Вот моя строка:python перемещать символы на основе строковой позиции

"th i s. i s. a. n i c^e . s t r i ng." 

Этот символ может появляться в любой точке. Я смог определить следующее пространство, но я все еще не могу его переместить.

То, что я сделал до сих пор это:

x= "th i s. i s. a. n i c^e . s t r i ng." 
for i in range(len(x)): 
    if x[i] == '^': 
     j = i + 1 
     if x[j] == ' ': 
      j = j + 1 
      while j < len(x) and x[j] != ' ': 
       j = j + 1 

      print "in the position " + str(i) + ", I found a hat: '" + str(x[i]) + "'" 
      print "in the position " + str(j) + ", I found the next space: '" + str(x[j]) + "'" 
      x.remove(i) 
      x.insert('^', j) 
     else: 
      print 'somebody help!' 
+3

ввод 'x =" th i s. I s. A. N i c^e. S t r i ng. "', Каков вам должен быть результат? – moenad

+0

строки не изменяемы ... вам нужно будет создать новую строку ... –

ответ

1

[Update]

Спасибо за все большие ответы. Я нашел решение своего вопроса после некоторого разговора с ним. Надеюсь, это поможет кому-то еще! :-)

x= "th i s. i s. a. n i^ c e. s s t. s t r i ng." 
for i in range(len(x)): 
    if x[i] == '^': 
     j = i + 1 
     if x[j] == ' ': 
      j = j + 1 
      while j < len(x) and x[j] != ' ': 
       j = j + 1 
       print x 
      x= x[0:i] + x[i+1:] 
      x= x[0:j-1] + "^" + x[j-1:] 
      print x 
      exit() 

результат: го я s. является. а. n i c^e. s s t. s t r i ng.

3

Строки неизменны, и они не имеют никакого remove или insert метод. Итак, сначала нужно преобразовать строку в список, а затем вы можете использовать list.remove и list.insert.

>>> x = "th i s. i s. a. n i c^e . s t r i ng." 
>>> list(x) 
['t', 'h', ' ', 'i', ' ', 's', '.', ' ', 'i', ' ', 's', '.', ' ', 'a', '.', ' ', 'n', ' ', 'i', ' ', 'c', ' ', '^', ' ', 'e', ' ', '.', ' ', 's', ' ', 't', ' ', 'r', ' ', 'i', ' ', 'n', 'g', '.'] 

И, наконец, после изменения списка вы можете присоединиться к нему обратно, используя str.join.

Ошибки в коде:

x.remove('^')  # you should remove '^' here, not the index 
x.insert(j, '^') # first argument is the index, second is the item 
+1

Если есть один специальный символ 'x.split ('^')', вероятно, будет быстрее. Только вторая подстрока должна быть проанализирована и обновлена, прежде чем объединять ее. –

+0

Я новичок в python и замечаю, что разрыв между функциями для списков и строк несколько пугает, но может быть преодолен небольшим ноу-хау. Спасибо за отличный ответ, это, безусловно, будет полезно в будущих кодах. :-) – badner

0

Я не уверен, я полностью понимаю вопрос, но вот несколько примеров того, как вы можете переместить символ в последовательности символов.

Перемещение персонажа к индексу

def move_char_index(chars, char, new_index): 
    # Convert character sequence to list type. 
    char_list = list(chars) 
    # Get the current index of the target character. 
    old_index = char_list.index(char) 
    # Remove the target character from the character list. 
    char = char_list.pop(old_index) 
    # Insert target character at a new location. 
    char_list.insert(new_index, char) 
    # Convert character list back to str type and return. 
    return ''.join(char_list) 

Примеры:

chars = 'th i s. i s. a. n i c ^e . s t r i ng.' 
char = '^' 

# Move character to the end of the string. 
print move_char_index(chars, char, len(chars)) 
# Result: th i s. i s. a. n i c e . s t r i ng.^ 

# Move character to the start of the string. 
print move_char_index(chars, char, 0) 
# Result: ^th i s. i s. a. n i c e . s t r i ng. 

Перемещение Характер По Приращение

def move_char_by_increment(chars, char, increment): 
    # Convert character sequence to list type. 
    char_list = list(chars) 
    # Get the current index of the target character. 
    old_index = char_list.index(char) 
    # Remove the target character from the character list. 
    char = char_list.pop(old_index) 
    # Insert target character at a new location. 
    new_index = old_index + increment 
    char_list.insert(new_index, char) 
    # Convert character list back to str type and return. 
    return ''.join(char_list) 

Примеры:

chars = 'th i s. i s. a. n i c ^e . s t r i ng.' 
char = '^' 

# Move character forward by 1. 
print move_char_by_increment(chars, char, 1) 
# Result: th i s. i s. a. n i c e^ . s t r i ng. 

# Move character backward by 1. 
print move_char_by_increment(chars, char, -1) 
# Result: th i s. i s. a. n i c^e . s t r i ng. 
Смежные вопросы