Changing string to uppercase in python - python

I' trying to change my variable to uppercase and I don't know what I'm getting wrong. Sample code:
Quacks = "time"
Quacks.upper()
print(Quacks)
When I run the above code, time is returned instead of TIME.

Method upper() does not change the value of variable, it only returns a string where all characters are in upper case.
So, you may print it directly:
print(Quacks.upper())
or change first and then print:
Quacks = Quacks.upper()
print(Quacks)

In Python str.upper() returns a copy of the string with upper case values, and does not mutate the original string. In fact, strings in Python are immutable anyways.
Try: Quacks = Quacks.upper()
Source: https://docs.python.org/3/library/stdtypes.html
"str.upper() - Return a copy of the string with all the cased characters [...] converted to uppercase."

Related

python changing string quotes [duplicate]

I want to check whether the given string is single- or double-quoted. If it is single quote I want to convert it to be double quote, else it has to be same double quote.
There is no difference between "single quoted" and "double quoted" strings in Python:
both are parsed internally to string objects.
I mean:
a = "European Swallow"
b = 'African Swallow'
Are internally string objects.
However you might mean to add an extra quote inside an string object, so that the content itself show up quoted when printed/exported?
c = "'Unladen Swallow'"
If you have a mix of quotes inside a string like:
a = """ Merry "Christmas"! Happy 'new year'! """
Then you can use the "replace" method to convert then all into one type:
a = a.replace('"', "'")
If you happen to have nested strings, then replace first the existing quotes to escaped quotes, and later the otuer quotes:
a = """This is an example: "containing 'nested' strings" """
a = a.replace("'", "\\\'")
a = a.replace('"', "'")
Sounds like you are working with JSON. I would just make sure it is always a double quoted like this:
doubleQString = "{0}".format('my normal string')
with open('sampledict.json','w') as f:
json.dump(doubleQString ,f)
Notice I'm using dump, not dumps.
Sampledict.json will look like this:
"my normal string"
In my case I needed to print list in json format.
This worked for me:
f'''"inputs" : {str(vec).replace("'", '"')},\n'''
Output:
"inputs" : ["Input_Vector0_0_0", "Input_Vector0_0_1"],
Before without replace:
f'"inputs" : {vec},\n'
"inputs" : ['Input_Vector0_0_0', 'Input_Vector0_0_1'],
The difference is only on input. They are the same.
s = "hi"
t = 'hi'
s == t
True
You can even do:
"hi" == 'hi'
True
Providing both methods is useful because you can for example have your string contain either ' or " directly without escaping.
In Python, there is no difference between strings that are single or double quoted, so I don't know why you would want to do this. However, if you actually mean single quote characters inside a string, then to replace them with double quotes, you would do this: mystring.replace('\'', '"')
Actually, none of the answers above as far as I know answers the question, the question how to convert a single quoted string to a double quoted one, regardless if for python is interchangeable one can be using Python to autogenerate code where is not.
One example can be trying to generate a SQL statement where which quotes are used can be very important, and furthermore a simple replace between double quote and single quote may not be so simple (i.e., you may have double quotes enclosed in single quotes).
print('INSERT INTO xx.xx VALUES' + str(tuple(['a',"b'c",'dfg'])) +';')
Which returns:
INSERT INTO xx.xx VALUES('a', "b'c", 'dfg');
At the moment I do not have a clear answer for this particular question but I thought worth pointing out in case someone knows. (Will come back if I figure it out though)
If you're talking about converting quotes inside a string, One thing you could do is replace single quotes with double quotes in the resulting string and use that. Something like this:
def toDouble(stmt):
return stmt.replace("'",'"')

Remove "." and "\" from a string

my project is to capture a log number from Google Sheet using gspread module. But now the problem is that the log number captured is in the form of string ".\1300". I only want the number in the string but I could not remove it using the below code.
Tried using .replace() function to replace "\" with "" but failed.
a='.\1362'
a.replace('\\',"")
Should obtain the string "1362" without the symbol.
But the result obtained is ".^2"
The problem is that \136 has special meaning (similar to \n for newline, \t for tab, etc). Seemingly it represents ^.
Check out the following example:
a = '.\1362'
a = a.replace('\\',"")
print(a)
b = r'.\1362'
b = b.replace('\\',"")
print(b)
Produces
.^2
.\1362
Now, if your Google Sheets module sends .\1362 instead of .\\1362, if is very likely because you are in fact supposed to receive .^2. Or, there's a problem with your character encoding somewhere along the way.
The r modifier I put on the b variable means raw string, meaning Python will not interpret backlashes and leave your string alone. This is only really useful when typing the strings in manually, but you could perhaps try:
a = r'{}'.format(yourStringFromGoogle)
Edit: As pointed out in the comments, the original code did in fact discard the result of the .replace() method. I've updated the code, but please note that the string interpolation issue remains the same.
When you do a='.\1362', a will only have three bytes:
a = '.\1362'`
print(len(a)) # => 3
That is because \132 represents a single character. If you want to create a six byte string with a dot, a slash, and the digits 1362, you either need to escape the backslash, or create a raw string:
a = r'.\1362'
print(len(a)) # => 6
In either case, calling replace on a string will not replace the characters in that string. a will still be what it was before calling replace. Instead, replace returns a new string:
a = r'.\1362'
b = a.replace('\\', '')
print(a) # => .\1362
print(b) # => .1362
So, if you want to replace characters, calling replace is the way to do it, but you've got to save the result in a new variable or overwrite the old.
See String and Bytes literals in the official python documentation for more information.
Your string should contains 2 backslashes like this .\\1362 or use r'.\1362' (which is declaring the string as raw and then it will be converted to normal during compile time). If there is only one backslash, Python will understand that \136 mean ^ as you can see (ref: link)
Whats happening here is that \1362 is being encoded as ^2 because of the backslash, so you need to make the string raw before you're able to use it, you can do this by doing
a = r'{}'.format(rawInputString)
or if you're on python3.6+ you can do
a = rf'{rawInputString}'

python attribute error?

I'm working on a simple python game in which the player attempts to guess letters contained in a word. The problem is, when I print a word, it's printing the \n at the end.
It looks like I need to use .strip to remove it. However, when I use it as seen in the following code, I get an attribute error saying that the list object has no attribute "strip".
Sorry for the newbie question.
import random
with open('wordlist.txt') as wordList:
secretWord = random.sample(wordList.readlines(), 1).strip()
print (secretWord)
Well, that's because lists don't have an attribute named strip. If you try print secretWord you'll notice that it's a list (of length 1), not a string. You need to access the string contained in that list, rather than the list itself.
secretWord = random.sample(wordList.readlines(), 1)[0].strip()
Of course, this would be much easier/cleaner if you used choice instead of sample, since you're only grabbing one word:
secretWord = random.choice(wordList.readlines()).strip()
Right. Strings in Python are not lists -- you have to convert between the two (though they often behave similarly).
If you'd like to turn a list of string into a string, you can join on the empty string:
x = ''.join(list_of_strings)
x is now a string. You'll have to do something similar to get from what you got out of random.sample (a list) to a string.
print adds a newline. You need to use something lower level, like os.write
random.sample() will return a list, it looks like you are trying to randomly select a single element from the list so you should use random.choice() instead:
import random
with open('wordlist.txt') as wordList:
secretWord = random.choice(wordList.readlines()).strip()
print (secretWord)

Python efficient mass replacing unknown characterers

PHP4+mySQL4 based project post to Django 1.1 project and it mixes up some letters.
What is the best way (most efficient) to replace in this fashion?
The problem for me is that i cannot get values for those letters. Is there an online tool to do that?
I have textField with various letters and i want to replace those in this fashion:
àèæëáðøûþ => ąčęėįšųūž
ÀÈÆËÁÐØÛÞ => ĄČĘĖĮŠŲŪŽ
I had similar case where i had to clean up the code so i used this:
def clean(string):
return ''.join([c for c in string if ord(c) > 31 or ord(c) in [9, 10, 13]] )
Update: i succeeded to extract Unicode values looking at Django debug messages (replace_from:replace_to):
{'\xe0':'\u0105', '\xe8':'\u010d', '\xe6':'\u0119', '\xeb':'\u0117', '\xe1':'\u012f',
'\xf0':'\u0161', '\xf8':'\u0179', '\xfb':'\u016b', '\xfe':'\u017e',
'\xc0':'\u0104', '\xc8':'\u010c', '\xc6':'\u0118', '\xcb':'\u0116', '\xc1':'\u012e',
'\xd0':'\u0160', '\xd8':'\u0172', '\xdb':'\u016a', '\xde':'\u017d'
So the main problem remains - replacing
Try the str.replace() method - should work with unicode strings.
str.replace(old, new[, count])
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
Make sure your old and new strings are of type Unicode
(that applies to your input data as well).
Find out what your input (non-unicode) string is supposed to be encoded in.
For example, it may be in latin1 encoding.
Use the builtin str.decode() method to create a Unicode version of your data,
and feed that to str.replace().
>>> unioldchars = oldchars.decode("latin1")
>>> newdata = data.replace(unioldchars, newchars)
I'd do it myself. The built-in replace function is of little use if you want multiple, efficient replacements.
Give this a look: http://code.activestate.com/recipes/81330-single-pass-multiple-replace/
EDIT: WAIT, you wanted to do the replacement client-side, like in the text-box?
string.translate(s, table[, deletechars])
Delete all characters from s that are in deletechars (if
present), and then translate the characters using table, which must be
a 256-character string giving the translation for each character value,
indexed by its ordinal. If table is None, then only the character deletion
step is performed.
See also http://docs.python.org/library/string.html#string.maketrans

Convert single-quoted string to double-quoted string

I want to check whether the given string is single- or double-quoted. If it is single quote I want to convert it to be double quote, else it has to be same double quote.
There is no difference between "single quoted" and "double quoted" strings in Python:
both are parsed internally to string objects.
I mean:
a = "European Swallow"
b = 'African Swallow'
Are internally string objects.
However you might mean to add an extra quote inside an string object, so that the content itself show up quoted when printed/exported?
c = "'Unladen Swallow'"
If you have a mix of quotes inside a string like:
a = """ Merry "Christmas"! Happy 'new year'! """
Then you can use the "replace" method to convert then all into one type:
a = a.replace('"', "'")
If you happen to have nested strings, then replace first the existing quotes to escaped quotes, and later the otuer quotes:
a = """This is an example: "containing 'nested' strings" """
a = a.replace("'", "\\\'")
a = a.replace('"', "'")
Sounds like you are working with JSON. I would just make sure it is always a double quoted like this:
doubleQString = "{0}".format('my normal string')
with open('sampledict.json','w') as f:
json.dump(doubleQString ,f)
Notice I'm using dump, not dumps.
Sampledict.json will look like this:
"my normal string"
In my case I needed to print list in json format.
This worked for me:
f'''"inputs" : {str(vec).replace("'", '"')},\n'''
Output:
"inputs" : ["Input_Vector0_0_0", "Input_Vector0_0_1"],
Before without replace:
f'"inputs" : {vec},\n'
"inputs" : ['Input_Vector0_0_0', 'Input_Vector0_0_1'],
The difference is only on input. They are the same.
s = "hi"
t = 'hi'
s == t
True
You can even do:
"hi" == 'hi'
True
Providing both methods is useful because you can for example have your string contain either ' or " directly without escaping.
In Python, there is no difference between strings that are single or double quoted, so I don't know why you would want to do this. However, if you actually mean single quote characters inside a string, then to replace them with double quotes, you would do this: mystring.replace('\'', '"')
Actually, none of the answers above as far as I know answers the question, the question how to convert a single quoted string to a double quoted one, regardless if for python is interchangeable one can be using Python to autogenerate code where is not.
One example can be trying to generate a SQL statement where which quotes are used can be very important, and furthermore a simple replace between double quote and single quote may not be so simple (i.e., you may have double quotes enclosed in single quotes).
print('INSERT INTO xx.xx VALUES' + str(tuple(['a',"b'c",'dfg'])) +';')
Which returns:
INSERT INTO xx.xx VALUES('a', "b'c", 'dfg');
At the moment I do not have a clear answer for this particular question but I thought worth pointing out in case someone knows. (Will come back if I figure it out though)
If you're talking about converting quotes inside a string, One thing you could do is replace single quotes with double quotes in the resulting string and use that. Something like this:
def toDouble(stmt):
return stmt.replace("'",'"')

Categories