Skip to content

Tag: string

Find and replace string values in list [duplicate]

This question already has answers here: Apply function to each element of a list (4 answers) Closed 5 months ago. The community reviewed whether to reopen this question 5 months ago and left it closed: Original close reason(s) were not resolved I got this list: What I would like is to replace [br] with some f…

Split a string at newline characters

I have a string, say How do we split the above with the delimiter n (a newline)? The result should be Answer If you are concerned only with the trailing newline, you can do: See, str.lstrip() and str.strip() for variations. If you are more generally concerned by superfluous newlines producing empty items, you…

What is the most efficient string concatenation method in Python?

Is there an efficient mass string concatenation method in Python (like StringBuilder in C# or StringBuffer in Java)? I found following methods here: Simple concatenation using + Using a string list and the join method Using UserString from the MutableString module Using a character array and the array module …

How to replace whitespaces with underscore?

I want to replace whitespace with underscore in a string to create nice URLs. So that for example: Should become I am using Python with Django. Can this be solved using regular expressions? Answer You don’t need regular expressions. Python has a built-in string method that does what you need:

How do I reverse a string in Python?

There is no built in reverse function for Python’s str object. What is the best way of implementing this method? If supplying a very concise answer, please elaborate on its efficiency. For example, whether the str object is converted to a different object, etc. Answer Using slicing: Slice notation takes…

How to remove the left part of a string?

I have some simple python code that searches files for a string e.g. path=c:path, where the c:path part may vary. The current code is: What is a simple way to get the text after Path=? Answer Starting in Python 3.9, you can use removeprefix:

Why is it string.join(list) instead of list.join(string)?

This has always confused me. It seems like this would be nicer: Than this: Is there a specific reason it is like this? Answer It’s because any iterable can be joined (e.g, list, tuple, dict, set), but its contents and the “joiner” must be strings. For example: Using something other than stri…