I'm trying to remove the single quotation marks from "'I'm'" to have "I'm" in the end. I tried the replace() and translate() buils-in methods but neither of them does what I want. This is what I tried
string = "'I'm'"
for ch in string:
if ch == "'" and (string[0] == ch or string[-1] == ch):
string = string.replace(ch, "")
I tried other ways but keeps on returning "Im" as output.
Your code has a few flaws:
Why are you iterating over the string if the only thing you need to check is the first and the last character?
While iterating a string you should not change it. It leads to unexpected and undesired consequences.
Your Boolean logic seems odd.
You are replacing all of the quotes in the first loop.
What would work is this:
if string[0] == "'" and string[-1] == "'" and len(string) > 1:
string = string[1:-1]
Where you do pretty much the same checks you want but you just remove the quotations instead of alternating the inner part of the string.
You could also use string.strip("'") but it is potentially going to do more than you wish removing any number of quotes and not checking if they are paired, e.g.
"'''three-one quotes'".strip("'")
> three-one quotes
Just use strip:
print(string.strip("'"))
Otherwise try this:
if (string[0] == "'") or (string[-1] == "'"):
string = string[1:-1]
print(string)
Both codes output:
I'm
To remove leading and trailing characters from a string you will want to use the str.strip method instead:
string = "'I'm'"
string = string.strip("'")
Related
I need to print a string, using this rules:
The first letter should be capital and make all other letters are lowercase. Only the characters a-z A-Z are allowed in the name, any other letters have to be deleted(spaces and tabs are not allowed and use underscores are used instead) and string could not be longer then 80 characters.
It seems to me that it is possible to do it somehow like this:
name = "hello2 sjsjs- skskskSkD"
string = name[0].upper() + name[1:].lower()
lenght = len(string) - 1
answer = ""
for letter in string:
x = letter.isalpha()
if x == False:
answer = string.replace(letter,"")
........
return answer
I think it's better to use a for loop or isalpha () here, but I can't think of a better way to do it. Can someone tell me how to do this?
For one-to-one and one-to-None mappings of characters, you can use the .translate() method of strings. The string module provides lists (strings) of the various types of characters including one for all letters in upper and lowercase (string.ascii_letters) but you could also use your own constant string such as 'abcdef....xyzABC...XYZ'.
import string
def cleanLetters(S):
nonLetters = S.translate(str.maketrans('','',' '+string.ascii_letters))
return S.translate(str.maketrans(' ','_',nonLetters))
Output:
cleanLetters("hello2 sjsjs- skskskSkD")
'hello_sjsjs_skskskSkD'
One method to accomplish this is to use regular expressions (regex) via the built-in re library. This enables the capturing of only the valid characters, and ignoring the rest.
Then, using basic string tools for the replacement and capitalisation, then a slice at the end.
For example:
import re
name = 'hello2 sjsjs- skskskSkD'
trans = str.maketrans({' ': '_', '\t': '_'})
''.join(re.findall('[a-zA-Z\s\t]', name)).translate(trans).capitalize()[:80]
>>> 'Hello_sjsjs_skskskskd'
Strings are immutable, so every time you do string.replace() it needs to iterate over the entire string to find characters to replace, and a new string is created. Instead of doing this, you could simply iterate over the current string and create a new list of characters that are valid. When you're done iterating over the string, use str.join() to join them all.
answer_l = []
for letter in string:
if letter == " " or letter == "\t":
answer_l.append("_") # Replace spaces or tabs with _
elif letter.isalpha():
answer_l.append(letter) # Use alphabet characters as-is
# else do nothing
answer = "".join(answer_l)
With string = 'hello2 sjsjs- skskskSkD', we have answer = 'hello_sjsjs_skskskSkD';
Now you could also write this using a generator expression instead of creating the entire list and then joining it. First, we define a function that returns the letter or "_" for our first two conditions, and an empty string for the else condition
def translate(letter):
if letter == " " or letter == "\t":
return "_"
elif letter.isalpha():
return letter
else:
return ""
Then,
answer = "".join(
translate(letter) for letter in string
)
To enforce the 80-character limit, just take answer[:80]. Because of the way slices work in python, this won't throw an error even when the length of answer is less than 80.
I have a string lets say something like below:
abc$defg..hij/klmn
How can I get substring which is cut out from last character until we encounter the $ sign. Note $ could be a special character and there could other special characters in the string.
The output should be:
defg..hij/klmn
I a using python 2.7 and above.
That is an alternate method. It checks each character from the end until a special character is met.
text = "abc$defg..hij/klmn"
newstring = text[::-1]
output = ""
for character in newstring:
if character != "$":
output += character
else:
break
print(output[::-1])
You could use the split function:
your_string = "abc$defg..hij/klmn"
split_char = "$"
substring = your_string.split(split_char)[-1]
You'll need to first get the occurrence of that first character and then slice from that index plus 1:
testStr = "abc$defg..hij/klmn"
try:
index = testStr.index()
start = index + 1
print(str[start:])
except:
print("Not in string")
Note: This will return a single string from after the first & to the end. If you want multiple strings enclosed within $, the accepted answer works well.
I have an input string 'java'. I want to replace only 2 '-'s in '----' with 'a' (I want them positioned in their right index) so that I have -a-a.
How do I achieve this?
Not sure exactly what you want, but from the description you can try something like this.
keyString = "java"
targetString = ""
for i in range(len(keyString)):
if keyString[i] == 'a': targetString += 'a'
else: targetString += '-'
Sorry if I misinterpret your question. I am reading the description as "I am given an input string and need to create another string that replaces all non-'a' characters in the input string with '-'.
The most straight-forward way to do this is to iterate through the input string and build the new string as you go, concatenating either a '-' or a 'a' to the new string depending on the current character in the input string. See below...
# The given input string and the start of the new string that we will create
inputString = "java"
newString = ""
# Go through each character in the input string to determine
# which character to add to the new string at each position
for character in inputString:
if character == 'a':
newString += 'a'
else:
newString += '-'
Basically im making a small piece of code to remove the end character of a string until the string passes .isdigit.
def string_conversion(string):
for i in string:
if i.isdigit == False:
string = string[0:len[string]-1]
print(string) #This is just here to see if it goes through
test = "60+"
string_conversion(test)
I used http://www.pythontutor.com/visualize.html to see why I wasn't getting any output, it passed a + symbol as a digit, just like the numbers 6 and 0.
Am I doing something wrong or does python treat + as a digit?
str.isdigit is a method not an attribute, so (as was already mentioned in the comments) you need to call it.
Also you check each character (starting from the left side) for isdigit but if it's not passing the isdigit() test you remove a character from the right side. That doesn't seem right. You probably wanted to iterate over the for i in reversed(string) (or using slicing: for i in string[::-1]).
But you also could simplify the logic by using a while loop:
def string_conversion(string):
while string and not string.isdigit():
string = string[:-1]
return string
def string_conversion(string):
for i, s in enumerate(string):
if s.isdigit() == False:
string = string[:i]
break
print(string) #This is just here to see if it goes through
test = "60+"
string_conversion(test)
Try This
can someone please tell me how to fix this? after the last seperator, the code stops and doesn't reach the end of the original string
def split_on_separators(original, separators):
""" (str, str) -> list of str
Return a list of non-empty, non-blank strings from original,
determined by splitting original on any of the separators.
separators is a string of single-character separators.
>>> split_on_separators("Hooray! Finally, we're done.", "!,")
['Hooray', ' Finally', " we're done."]
"""
result = []
newstring=''
for char in original:
if char in separators:
result.append(newstring)
newstring = ""
else:
newstring += char
return result
import re
def split_on_separators(original, separators):
return re.split("[" + separators + "]", original)
OK, this isn't perfect because certain characters cannot appear in separators because it's used to build a regex, but it works for many cases including the one in the question. A more robust way would be to simply use re.split instead of this function in the first place.
You need to append newstring to result once the loop is completed / before you return. Since there are no separators after the last string it will otherwise never get added since only encountering a separator causes appendage to the list.
The code only puts a part of the input string in result when it hits a separator. Since there is no separator at the end of your sample input, the "we're done" in newstring is not appended to result. To fix this you would have add an if statement after the for to see if there was something in newstring, and then append it if necessary.