Sunday, August 4, 2019

Delete /n at end of a String (Python)





How can I delete a /n linebreak at the end of a String ?



I´m trying to read two strings from an .txt file and want to format them with os.path.join() method after I "cleared" the string.



Here you can see my try with dummy data:



content = ['Source=C:\\Users\\app\n', 'Target=C:\\Apache24\\htdocs']

for string in content:
print(string)

if string.endswith('\\\n'):
string = string[0:-2]

print(content)

Answer



You can not update a string like you are trying to. Python strings are immutable. Every time you change a string, new instance is created. But, your list still refers to the old object. So, you can create a new list to hold updated strings. And to strip newlines you can use rstrip function. Have a look at the code below,



content = ['Source=C:\\Users\\app\n', 'Target=C:\\Apache24\\htdocs']
updated = []

for string in content:
print(string)
updated.append(string.rstrip())

print(updated)

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...