This question already has answers here:
Why doesn't calling a string method (such as .replace or .strip) modify (mutate) the string?
(3 answers)
Closed 3 years ago.
Lest say I have string like this:
string = "hello world"
I want to have only praticular letter uppercased so if i choose second letter my output should look like this:
hEllo wold
But if i try for example:
string[1].upper()
My output is:
hello world
And not:
hEllo wold
I dont know why...
This line:
string[1].upper()
Isn't doing what you think. Sure, it uppercases the value in string[1], but it returns a new string with the result! - because in Python strings are immutable. Now, you'd be tempted to think that this would fix it:
string[1] = string[1].upper()
... But no, this will fail because once again - strings are immutable. You have no choice but to create a new string, with some logic to tell which positions you want to uppercase. For example, to uppercase the value at index = 1:
''.join(c.upper() if i == 1 else c for i, c in enumerate(string))
To capitalize only one letter of a string you have to capitalize the part of the string starting from the nth position, and assign it back to the variable:
string = string[:n] + string[n:].capitalize()
In Python Strings are not Modifiable hence the operation that you specified would not work.
In order to make this work,you can convert the string to a list and then convert a particular character to uppercase and then join the result back into a string.
sample_str="hello world"
sample_list=list(sample_str)
sample_list[2]=sample_list[2].upper()
print(''.join(str(i) for i in sample_list))
Related
This question already has answers here:
Why doesn't calling a string method (such as .replace or .strip) modify (mutate) the string?
(3 answers)
Closed 3 years ago.
I'm working through the Python course on codecademy and trying to create a python function that removes vowels in a string and returns the newly modified string.However the function returns the string without any modification (i.e. if I call anti_vowel("abcd") it returns "abcd")
After using a print statement it appears the for loop only runs once, irrespective of the length of the string.
def anti_vowel(string):
for t in string:
if(t.lower()=='a' or t.lower()=='e' or t.lower()=='i' or t.lower()=='u'):
string.replace(t, " ")
print "test"
print string
return string
Strings in Python are immutable, so you will need to make an assignment back to the original string with the replacement on the RHS:
if (t.lower()=='a' or t.lower()=='e' or t.lower()=='i' or t.lower()=='u'):
string = string.replace(t, " ")
But, you could also just re.sub here:
string = re.sub(r'[aeiou]+', '', string, flags=re.IGNORECASE)
You have the return statement inside the for a loop that is why your code is your loop is executing exactly once. Place it outside the loop and your code will work fine.
def anti_vowel(string):
for t in string:
if(t.lower()=='a' or t.lower()=='e' or t.lower()=='i' or t.lower()=='u'):
string.replace(t, " ")
print "test"
print string
return string
For replacing the vowel characters, you cannot replace in the existing variable as strings in python are immutable. You can try this
def anti_vowel(string):
for t in string:
if(t.lower()=='a' or t.lower()=='e' or t.lower()=='i' or t.lower()=='u'):
string=string.replace(t, " ")
print "test"
print string
return string
This question already has answers here:
What is the difference between __str__ and __repr__?
(28 answers)
Closed 6 years ago.
I have a list of strings: ['John','William','Ken','Rogers']. I need to prepend "Corp\" to each element in the list so that the final list looks like this:
['Corp\John','Corp\William','Corp\Ken','Corp\Rogers']
I tried the following:
s=['John','William','Ken','Rogers']
users=['Corp\\' + m for m in s]
print(users)
The output gives me
['Corp\\John','Corp\\William','Corp\\Ken','Corp\\Rogers']
If I try users=['Corp\' + m for m in s] I get an obvious error:
"StringError EOL while scanning string literal"
I would need each element in the exact form 'Corp\name', as this needs to be used in a for loop to validate users who are eligible to login.
This may be a problem with how you're 'outputting' the list. Using the REPL:
>>> lsa = ["Corp\{}".format(item) for item in ls]
>>> print(lsa)
['Corp\\Jenna', 'Corp\\Wilma', 'Corp\\Katie', 'Corp\\Rebecca']
>>> for i in lsa:
... print(i)
...
Corp\Jenna
Corp\Wilma
Corp\Katie
Corp\Rebecca
As you can see, in the first print, that prints the full list, we see two slashes. This is because Python is saying that the second slash is escaped. In the second print, inside a for loop, we see that there is only one slash, because we are printing each item individually and the escape string is applied, yielding only a single slash.
This question already has answers here:
How can I invert (swap) the case of each letter in a string?
(8 answers)
Closed 7 years ago.
I'm rank new in Python, thus the question,
I'm trying to solve a simple problem, where the program takes in a simple string and swaps all the cases. Thus if we enter
SimPLE
We should get
sIMple
This is my code
def main():
oldStr = input()
for s in oldStr:
if s.islower():
s.upper()
elif s.isupper():
s.lower()
print(oldStr)
if __name__ == "__main__" : main()
It just returns the same string. Any help appreciated.
As a generator expression:
mystr = "SimPLE"
print("".join(c.upper() if c.islower() else c.lower() for c in mystr))
The breakdown of the above is:
c.upper() if c.islower() else c.lower()
is an conditional expression that will convert a character from upper to lower case and vice versa.
Then,
(... for c in mystr)
is a generator expression, which is somewhat like a list that is generated on-the-fly.
Finally:
".join(...)
will join any sequence of strings together with nothing ("") between them.
Do this in one fell swoop with a string join on a list comprehension of individual characters:
outstr = ''.join([s.upper() if s.islower() else s.lower() for s in oldStr])
print(outstr)
Input & Output:
sIMple
SimPLE
Strings are immutable. What this means is that when you use the function s.upper(), it is not setting that letter in str to be uppercase, it simply returns that letter in uppercase.
Here is some code that works:
def main():
oldStr = input()
newStr = ""
for s in oldStr:
if s.islower():
newStr+=s.upper()
elif s.isupper():
newStr+=s.lower()
print(newStr)
Notice now that we are creating a new string and simply adding the letters at each point in the forloop as opposed to changing those letters in str.
You are running each character through lower() and upper(), but these functions do not change the character.
Instead, they return the modified version of the character. The original character s will stay as it is.
You should build a new string based off the return values of lower() and upper(), and return that string.
1) you need to put the main() call on new line, as python relies on whitespace heavily for program structure
2) s is a temporary variable created for the purpose of the for statement. It doesn't actually reference the character in the string
Essentially what is going on is that s has the same value as the character in the string, but it IS NOT ACTUALLY the character in the string.
This question already has answers here:
Why doesn't calling a string method (such as .replace or .strip) modify (mutate) the string?
(3 answers)
Closed 8 years ago.
I'm trying to remove a set of characters from a larger string. Here's what I've tried:
string = 'aabc'
remove = 'ac'
for i in remove:
string.replace(i, '', 1)
print(string)
I keep getting back my original string when I run this. The variable i is getting the characters 'a' and then 'c'. The replace function works for me if i do string.replace('a', '', 1). Why isn't this working or is there a simpler way to do this?
Strings are immutable in python, so string.replace() does not mutate the string; it returns a new string with the replacements.
Try this:
string = string.replace(i, '', 1)
replace returns a new string.
Strings in python are immutable.
As such, you must assign the return value:
string_new = "ABCD".replace("A","Z")
A new string will be generated as Strings are immutable...
Try this -
string = 'aabc'
remove = 'ac'
for i in remove:
result = string.replace(i, '', 1)
print(result)
As Strings are immutable you cant use replace with just string.replace().
As a better way use set :
>>> s='aabcc'
>>> s=''.join(set(s))
'acb'
This question already has answers here:
Python: Cut off the last word of a sentence?
(10 answers)
Closed 8 years ago.
Is there any efficient way to select the last characters of a string until there's a whitespace in Python?
For example I have the following string:
str = 'Hello my name is John'
I want to return 'John'. But if the str was:
str = 'Hello my name is Sally'
I want to retrun 'Sally'
Just split the string on whitespace, and get the last element of the array. Or use rsplit() to start splitting from end:
>>> st = 'Hello my name is John'
>>> st.rsplit(' ', 1)
['Hello my name is', 'John']
>>>
>>> st.rsplit(' ', 1)[1]
'John'
The 2nd argument specifies the number of split to do. Since you just want last element, we just need to split once.
As specified in comments, you can just pass None as 1st argument, in which case the default delimiter which is whitespace will be used:
>>> st.rsplit(None, 1)[-1]
'John'
Using -1 as index is safe, in case there is no whitespace in your string.
It really depends what you mean by efficient, but the simplest (efficient use of programmer time) way I can think of is:
str.split()[-1]
This fails for empty strings, so you'll want to check that.
I think this is what you want:
str[str.rfind(' ')+1:]
this creates a substring from str starting at the character after the right-most-found-space, and up until the last character.
This works for all strings - empty or otherwise (unless it's not a string object, e.g. a None object would throw an error)