Are there limits to using string.lstrip() in python? [duplicate] - python

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Is this a bug in Python 2.7?
The .lstrip() function doesn't quite work as I expected on some strings (especially ones with underscores). e.g.,
In [1]: a='abcd_efg_hijk_lmno_pqrs_tuvw_xyz'
In [2]: a.lstrip('abcd_efg')
Out[2]: 'hijk_lmno_pqrs_tuvw_xyz'
Here, the '_' between 'g' and 'h' is missing. Any idea as to why this happens?

.lstrip() doesn't do what you think it does. It removes any of the provided characters from the left end of the string. The second underscore is as much an underscore as the first, so it got removed too.
"aaaaaaaabbbbbbbc".lstrip("ab") # "c"

What you want:
b = 'abcd_efg'
if a.startswith(b):
a = a[len(b):]
As the str.lstrip documentation says,
The chars argument is not a prefix; rather, all combinations of its values are stripped:
>>> 'www.example.com'.lstrip('cmowz.')
'example.com'

To do what you want:
>>> a = "foobar"
>>> sub = "foo"
>>> b = a[len(sub):]
>>> b
'bar'

Related

python string strip weird behavior [duplicate]

This question already has answers here:
How do the .strip/.rstrip/.lstrip string methods work in Python?
(4 answers)
Closed 4 years ago.
Is there a reason why I am having this kind of string strip behavior ? Is this a bug or some string magic I am missing
# THIS IS CORRECT
>>> 'name.py'.rstrip('.py')
'name'
# THIS IS WRONG
>>> 'namey.py'.rstrip('.py')
'name'
# TO FIX THE ABOVE I DID THE FOLLOWING
>>> 'namey.py'.rstrip('py').rstrip('.')
'namey'
That's because the str.rstrip() command removes each trailing character, not the whole string.
https://docs.python.org/2/library/string.html
string.rstrip(s[, chars])
Return a copy of the string with trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the end of the string this method is called on.
This also generates same result
>>> 'nameyp.py'.rstrip('.py')
'name'
You could try str().endswith
>>> name = 'namey.py'
... if name.endswith('.py'):
... name = name[:-3]
>>> name
'namey'
Or just str().split()
>>> 'namey.py'.split('.py')[0]
'namey'

python 3 regex: match a character exactly once [duplicate]

This question already has answers here:
Match exact string
(3 answers)
Closed 4 years ago.
a sentence needs to contain 1 or more instances of 'a', exactly 1 instance of 'b' and 0 or more instances of 'c'
my expression is a+bc*
it works for strings like 'abc' 'ab' 'aabcc' which is all fine but it also works when i have multiple b's like 'abbc' which it shouldn't. How do i get it to work when theres only 1 'b'
Here is my full code
import re
qq = re.compile('a+bc*')
if qq.match('abb') is not None:
print("True")
else:
print('False')
which should produce False
Use qq=re.compile(r'^a+bc*$'). The ^ means match at start and $ means match at the end.
You want to match the pattern to the full string and not a part of it. That is why you need the ^ and $ in this case

Regex string insertion [duplicate]

This question already has answers here:
What exactly do "u" and "r" string prefixes do, and what are raw string literals?
(7 answers)
Closed 6 years ago.
Simple, simple question, hope you can help me:
How do I add a string to a regex?
Say:
d = '\d\d\d'
mo = re.compile(r #d goes here)
Pasting it, separating it with a comma, or with a plus gives me errors.
Normally, as you know, it would be re.compile(r'\d\d\d')
Is this what you are looking for?
d = r"\d\d\d"
re.compile(d)
Maybe more intuitive:
d = r"\d{3}"
# match a digit exactly three times, consecutively
re.compile(d)

how to change a character by its position in a string python [duplicate]

This question already has answers here:
Changing one character in a string
(15 answers)
Closed 8 years ago.
Im trying to make a Hangman game and I need to change certain characters in a string.
Eg: '-----', I want to change the third dash in this string, with a letter. This would need to work with a word of any length, any help would be greatly appreciated
Strings are immutable, make it a list and then replace the character, then turn it back to a string like so:
s = '-----'
s = list(s)
s[2] = 'a'
s = ''.join(s)
String = list(String)
String[0] = "x"
String = str(String)
Will also work. I am not sure which one (the one with .join and the one without) is more efficient
You can do it using slicing ,
>>> a
'this is really string'
>>> a[:2]+'X'+a[3:]
'thXs is really string'
>>>

Replacing characters in a string (Python) [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to replace a string in a function with another string in Python?
I want to enter any string with any type of character, and if the character is an alphabet, I want to replace it with "^" and get it printed.
For example, if my input is replace('text-here'), I should get the output as "^^^^-^^^^".
I've tried using the following statement, but it just prints whatever my input was. Please help!
def replace(string):
for x in range(len(string)):
string.replace(string[x],"^")
print(string)
I'm new to python, and don't know complex stuff. Please give me easy-to-understand answers. Thanks!
>>> text = 'text-here'
>>> ''.join('^' if c.isalpha() else c for c in text)
'^^^^-^^^^'
I think this is easy to understand but just in case here is code that shows what it does more simply:
>>> def replace(text):
new_text = ''
for c in text:
if c.isalpha():
new_text += '^'
else:
new_text += c
return new_text
>>> replace(text)
'^^^^-^^^^'
You could use Python's Regular Expressions library.
Like so,
import re
re.sub('\w', '^', 'text-here')
# Outputs: "^^^^-^^^^"
That's because string is immutable. string.replace(string[x],"^") returns a new object.
Modify
string.replace(string[x],"^")
to
string = string.replace(string[x],"^")
and it will work as expected.
Now that your question is on "but it just prints whatever my input was", I would like to tell you that the method str.replace will return a new string instead of to replace the string in place.
>>> a = "foo"
>>> a.replace("foo","bar")
'bar'
>>> a
'foo'
So you need to do string = string.replace(...)

Categories