6

What is the python syntax to insert a line break after every occurrence of character "X" ? This below gave me a list object which has no split attribute error

for myItem in myList.split('X'):
  myString = myString.join(myItem.replace('X','X\n'))
akash karothiya
  • 5,736
  • 1
  • 19
  • 29
user6284097
  • 157
  • 1
  • 1
  • 9

5 Answers5

15
myString = '1X2X3X'
print (myString.replace ('X', 'X\n'))
Jacques de Hooge
  • 6,750
  • 2
  • 28
  • 45
2

Python 3.X

myString.translate({ord('X'):'X\n'})

translate() allows a dict, so, you can replace more than one different character at time.

Why translate() over replace() ? Check translate vs replace

Python 2.7

myString.maketrans('X','X\n')
Community
  • 1
  • 1
levi
  • 22,001
  • 7
  • 73
  • 74
2

You can simply replace X by "X\n"

myString.replace("X","X\n")
Harsha Biyani
  • 7,049
  • 9
  • 37
  • 61
1

A list has no split method (as the error says).

Assuming myList is a list of strings and you want to replace 'X' with 'X\n' in each once of them, you can use list comprehension:

new_list = [string.replace('X', 'X\n') for string in myList]
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
1

Based on your question details, it sounds like the most suitable is str.replace, as suggested by @DeepSpace. @levi's answer is also applicable, but could be a bit of a too big cannon to use. I add to those an even more powerful tool - regex, which is slower and harder to grasp, but in case this is not really "X" -> "X\n" substitution you actually try to do, but something more complex, you should consider:

import re
result_string = re.sub("X", "X\n", original_string)

For more details: https://docs.python.org/2/library/re.html#re.sub

creativeChips
  • 1,177
  • 9
  • 12