Why doesn't calling a string method do anything unless its output is assigned?
This is because strings are immutable in Python.
Which means that X.replace("hello","goodbye")
returns a copy of X
with replacements made. Because of that you need replace this line:
X.replace("hello", "goodbye")
with this line:
X = X.replace("hello", "goodbye")
More broadly, this is true for all Python string methods that change a string's content "in-place", e.g. replace
,strip
,translate
,lower
/upper
,join
,...
You must assign their output to something if you want to use it and not throw it away, e.g.
X = X.strip(' \t')
X2 = X.translate(...)
Y = X.lower()
Z = X.upper()
A = X.join(':')
B = X.capitalize()
C = X.casefold()
and so on.
String method doesn`t work in Function // Python
You need to store the replace function return value in the same or diff variable.
testString = "Upper and Lower Case CALCULATION"
def case_counter(string, upperCount = 0, lowerCount = 0):
string = string.replace(" ","") # Modified
for i in string:
if i.isupper():
upperCount += 1
else:
lowerCount += 1
print("Upper Letters count: ", upperCount)
print("Lower Letters count: ", lowerCount)
case_counter(testString)
print("\n")
Also, I would like to suggest the best approach for this.
def case_counter(string):
string = string.replace(" ","")
upper_count = sum(i.isupper() for i in string)
lower_count = len(string) - upper_count
print("Upper Letters count: ", upper_count)
print("Lower Letters count: ", lower_count)
Why is this list not replacing the string values?
The i.replace()
returns the replaced string, but you have to assign it. So:
i = i.replace("hpp", "h")
Now i
will contain the replaced string.
Why string method on a string object doesn't modify the object in Python?
Strings are immutable types in python. Main advantages of being immutable would be:
- simplify multithreaded programming.
- can be used as dictionary keys (will keep the same hash)
Error encountered while changing case of the letter
You are not saving the lowercased string to a new variable. Try:
name1 = "name1".lower()
print(name1)
Why doesn't Python return an error for string assignment using replace in a for loop?
a.replace(i, "B")
does not change the original string a
. Instead, it returns the string which results from replacing i
in a
.
In your loop, you are merely evaluating an expression and dropping it on the floor.
You could do it this way:
a = "AECD"
for i in a:
if i == "E":
a = a.replace(i, "B")
print(a)
In this version, you take the string with the replacement, and you assign that value to the variable a
, which gives you the effect you were expecting.
Replacing character in string doesn't do anything
You can use re.sub
. In particular, note that it can take a function as repl
parameter. The function takes a match object, and returns the desired replacement based on the information the match object has (e.g., m.group(1)
).
import re
lst = ['Therefore', 'allowance', '(#)', 't(o)o', 'perfectly', 'gentleman', '(##)', 'su(p)posing', 'man', 'his', 'now']
def remove_paren(m):
return m.group(0) if m.group(1) in ('#', '##') else m.group(1)
output = [re.sub(r"\((.*?)\)", remove_paren, word) for word in lst]
print(output) # ['Therefore', 'allowance', '(#)', 'too', 'perfectly', 'gentleman', '(##)', 'supposing', 'man', 'his', 'now']
Related Topics
Why Does Comparing Strings Using Either '==' or 'Is' Sometimes Produce a Different Result
Evaluating a Mathematical Expression in a String
How to Parse an Iso 8601-Formatted Date
String Formatting: % Vs. .Format Vs. F-String Literal
Why Can't I Call Read() Twice on an Open File
How to Sort a Dictionary by Key
How to Make a Dictionary from Separate Lists of Keys and Values
Pygame Mouse Clicking Detection
Why Doesn't Calling a String Method Do Anything Unless Its Output Is Assigned
Error: Unable to Find Vcvarsall.Bat
How to Parse Xml and Get Instances of a Particular Node Attribute
Remap Values in Pandas Column With a Dict, Preserve Nans
How to Split a String into a List
How to Put a Variable'S Value Inside a String
How to Make a Python, Command-Line Program Autocomplete Arbitrary Things Not Interpreter