Empty strings are "falsy" (python 2 or python 3 reference), which means they are considered false in a Boolean context, so you can just do this:
if not myString:
This is the preferred way if you know that your variable is a string. If your variable could also be some other type then you should use:
if myString == "":
See the documentation on Truth Value Testing for other values that are false in Boolean contexts.
Answer from Andrew Clark on Stack OverflowEmpty strings are "falsy" (python 2 or python 3 reference), which means they are considered false in a Boolean context, so you can just do this:
if not myString:
This is the preferred way if you know that your variable is a string. If your variable could also be some other type then you should use:
if myString == "":
See the documentation on Truth Value Testing for other values that are false in Boolean contexts.
From PEP 8, in the “Programming Recommendations” section:
For sequences, (strings, lists, tuples), use the fact that empty sequences are false.
So you should use:
if not some_string:
or:
if some_string:
Just to clarify, sequences are evaluated to False or True in a Boolean context if they are empty or not. They are not equal to False or True.
Videos
import random
def shuffle(string):
templist = list(string)
random.shuffle(templist)
return "".join(templist)
usablelower = chr(random.randint(97, 122))
usableupper = chr(random.randint(65, 90))
usablenum = chr(random.randint(48, 57))
rst = random.choice(usableupper)
rst1 = random.choice(usablelower)
rst2 = random.choice(usablenum)
pw = rst1 + rst + rst2 + rst + rst2 + rst1
pw = shuffle(pw)
print(pw)Hello, I was trying to code a random password generator yet I could not understand the "return "".join(templist)" part. What is the use of empty string here, what does it do and why this code require it?
It's not possible. There are 2 reasons for that
Python strings are immutable
Python implements a so called "call by sharing" evaluation strategy:
The semantics of call by sharing differ from call by reference in that assignments to function arguments within the function aren't visible to the caller
As noted by zerkms, it is strictly not possible, python does not pass argument by reference.
There are a few tricks that can be used as workarounds, such as passing a list or object, containing your string.
otherText=["hello"]
def foo(text):
text[0]="Goodbye string"
foo(otherText)
print(otherText) //Goodbye string
I recently came across a problem in a textbook where these 2 were interchangeable. So what’s the difference between these 2 and when to use which? Thanks!
Edit for context:
would like to clarify the use of None in this question to initialize the while loop, how does it initialize the loop?
start = None
while start != “”: start = int(input(“Start: “) . . .
>>> '' in 'abc' True
can someone explain? (python 3.12.6)