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'))
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'))
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')
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]
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