5

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,500
  • 1
  • 16
  • 26
user6284097
  • 147
  • 1
  • 1
  • 7

5 Answers5

14
myString = '1X2X3X'
print (myString.replace ('X', 'X\n'))
Jacques de Hooge
  • 6,497
  • 2
  • 20
  • 39
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
  • 20,483
  • 7
  • 63
  • 71
2

You can simply replace X by "X\n"

myString.replace("X","X\n")
Harsha Biyani
  • 6,633
  • 9
  • 33
  • 55
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
  • 72,713
  • 11
  • 96
  • 140
0

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,119
  • 9
  • 12