Suppose we have a variable foo = "text" . How would you transform it to foo = '"text"' ? Is there a way of doing this without using the library urllib2 ?
Edit: Below is a script:
def most_common(lst):
if(len(lst) > 0):
return max(set(lst), key=lst.count)
else:
return 0
test_list = list(df['a'])) # a is a column that can take the the values '"apple"', '"pear"', '"carrot"'
test_list_most = most_common(test_list) # returns "apple"
But suppose we want to filter the data frame:
df = len(df[df['a'] == test_list_most].index) # length would be 0
That is the context for this question and why we want to add the single quotes around the double quotes.
Add the double quotation marks around it: '"' + foo + '"'. Or f'"{foo}"', if you prefer format strings.
Do you mean by:
print(f"'{foo}'")
Output:
'text'
Or:
print(f'"{foo}"')
Output:
"text"
You can escape the character like this
print("'\"Hello World\"'")
it'll give the output as
print("'\"Hello World\"'")
or when you need to assign to a variable
foo = "'\"Hello World\"'"
hope it answers your question
Related
I have the following string:
x = 'aaabbbbbaaaaaacccccbbbbbbbbbbbbbbb'. I want to get an output like this: abaacbbb, in which "a" will be compressed with a length of 3 and "b" will be compressed with a length of 5. I used the following function, but it removes all the adjacent duplicates and the output is: abacb :
def remove_dup(x):
if len(x) < 2:
return x
if x[0] != x[1]:
return x[0] + remove_dup(x[1:])
return remove_dup(x[1:])
x = 'aaabbbbbaaaaaacccccbbbbbbbbbbbbbbb'
print(remove_dup(x))
It would be wonderful if somebody could help me with this.
Thank you!
Unless this is a homework question with special constraints, this would be more conveniently and arguably more readably implemented with a regex substitution that replaces desired quantities of specific characters with a single instance of the captured character:
import re
def remove_dup(x):
return re.sub('(a){3}|([bc]){5}', r'\1\2', x)
x = 'aaabbbbbaaaaaacccccbbbbbbbbbbbbbbb'
print(remove_dup(x))
This outputs:
abaacbbb
I'm sure this is covered in plenty of places, but I don't know the exact name of the action I'm trying to do so I can't really look it up. I've been reading an official Python book for 30 minutes trying to find out how to do this.
Problem: I need to put a string in a certain length "field".
For example, if the name field was 15 characters long, and my name was John, I would get "John" followed by 11 spaces to create the 15 character field.
I need this to work for any string put in for the variable "name".
I know it will likely be some form of formatting, but I can't find the exact way to do this. Help would be appreciated.
This is super simple with format:
>>> a = "John"
>>> "{:<15}".format(a)
'John '
You can use the ljust method on strings.
>>> name = 'John'
>>> name.ljust(15)
'John '
Note that if the name is longer than 15 characters, ljust won't truncate it. If you want to end up with exactly 15 characters, you can slice the resulting string:
>>> name.ljust(15)[:15]
If you have python version 3.6 or higher you can use f strings
>>> string = "John"
>>> f"{string:<15}"
'John '
Or if you'd like it to the left
>>> f"{string:>15}"
' John'
Centered
>>> f"{string:^15}"
' John '
For more variations, feel free to check out the docs: https://docs.python.org/3/library/string.html#format-string-syntax
You can use rjust and ljust functions to add specific characters before or after a string to reach a specific length.
The first parameter those methods is the total character number after transforming the string.
Right justified (add to the left)
numStr = '69'
numStr = numStr.rjust(5, '*')
The result is ***69
Left justified (add to the right)
And for the left:
numStr = '69'
numStr = numStr.ljust(3, '#')
The result will be 69#
Fill with Leading Zeros
Also to add zeros you can simply use:
numstr.zfill(8)
Which gives you 00000069 as the result.
string = ""
name = raw_input() #The value at the field
length = input() #the length of the field
string += name
string += " "*(length-len(name)) # Add extra spaces
This will add the number of spaces needed, provided the field has length >= the length of the name provided
name = "John" // your variable
result = (name+" ")[:15] # this adds 15 spaces to the "name"
# but cuts it at 15 characters
I know this is a bit of an old question, but I've ended up making my own little class for it.
Might be useful to someone so I'll stick it up. I used a class variable, which is inherently persistent, to ensure sufficient whitespace was added to clear any old lines. See below:
2021-03-02 update: Improved a bit - when working through a large codebase, you know whether the line you are writing is one you care about or not, but you don't know what was previously written to the console and whether you want to retain it.
This update takes care of that, a class variable you update when writing to the console keeps track of whether the line you are currently writing is one you want to keep, or allow overwriting later on.
class consolePrinter():
'''
Class to write to the console
Objective is to make it easy to write to console, with user able to
overwrite previous line (or not)
'''
# -------------------------------------------------------------------------
#Class variables
stringLen = 0
overwriteLine = False
# -------------------------------------------------------------------------
# -------------------------------------------------------------------------
def writeline(stringIn, overwriteThisLine=False):
import sys
#Get length of stringIn and update stringLen if needed
if len(stringIn) > consolePrinter.stringLen:
consolePrinter.stringLen = len(stringIn)+1
ctrlString = "{:<"+str(consolePrinter.stringLen)+"}"
prevOverwriteLine = consolePrinter.overwriteLine
if prevOverwriteLine:
#Previous line entry can be overwritten, so do so
sys.stdout.write("\r" + ctrlString.format(stringIn))
else:
#Previous line entry cannot be overwritten, take a new line
sys.stdout.write("\n" + stringIn)
sys.stdout.flush()
#Update the class variable for prevOverwriteLine
consolePrinter.overwriteLine = overwriteThisLine
return
Which then is called via:
consolePrinter.writeline("text here", True)
If you want this line to be overwriteable
consolePrinter.writeline("text here",False)
if you don't.
Note, for it to work right, all messages pushed to the console would need to be through consolePrinter.writeline.
I generally recommend the f-string/format version, but sometimes you have a tuple, need, or want to use printf-style instead. I did this time and decided to use this:
>>> res = (1280, 720)
>>> '%04sx%04s' % res
'1280x 720'
Thought it was a touch more readable than the format version:
>>> f'{res[0]:>4}x{res[1]:>4}'
First check to see if the string's length needs to be shortened, then add spaces until it is as long as the field length.
fieldLength = 15
string1 = string1[0:15] # If it needs to be shortened, shorten it
while len(string1) < fieldLength:
rand += " "
Just whipped this up for my problem, it just adds a space until the length of string is more than the min_length you give it.
def format_string(str, min_length):
while len(str) < min_length:
str += " "
return str
I am trying to iterate over some integer values and insert them into an string which has to be in a weird format to work. The exact output (including the outer quotes) I need if the value was 64015 would be:
"param={\"zip\":\"64015\"}"
I have tried f string formatting but couldn't get it to work. It has problem with the backslashes and when I escaped them the output was not exactly like above string
Hopefully, I made myself clear enough.
You would have to escape the backslash and the double quotes seperately like this:
string = '"param={\\\"zip\\\":\\\"' + str(64015) + '\\\"}"'
The result of this is:
"param={\"zip\":\"64015\"}"
You can use alternate ways to delimit the outer string ('...', '''...''', """...""") or use str.format() or old style %-formatting syntax to get there (see f-style workaround at the end):
s = s = 'param={"zip":"' + str(64015) + '"}'
print(s)
s = '''param={"zip":"''' + str(64015) +'''"}'''
print(s)
s = """param={"zip":"64015"}""" # not suited for variable replacement
print(s)
s = 'param={{"zip":"{0}"}}'.format(64015)
print(s)
s = 'param={"zip":"%s"}' % 64015
print(s)
Output:
param={"zip":"64015"}
param={"zip":"64015"}
param={"zip":"64015"}
param={"zip":"64015"}
If you need any "\" in there simply drop a \\ in:
s = '"param={\\"zip\\":\\"' + str(64015) + '\\"}"'
print(s)
s = '''"param={\\"zip\\":\\"''' + str(64015) +'''\\"}"'''
print(s)
s = '"param={{\\"zip\\":\\"{0}\\"}}"'.format(64015)
print(s)
s = '"param={\\"zip\\":\\"%s\\"}"' % 64015
print(s)
Output:
"param={\"zip\":\"64015\"}"
"param={\"zip\":\"64015\"}"
"param={\"zip\":\"64015\"}"
"param={\"zip\":\"64015\"}"
The f-string workaround variant would look like so:
a = '\\"'
num = 64015
s = f'"param={{{a}zip{a}:{a}{num}{a}}}"'
and if printed also yields :
"param={\"zip\":\"64015\"}"
More on the topic can be found here: 'Custom string formatting' on python.org
I played around a bit with f-strings and .format() but ultimately got this to work:
foo = 90210
bar = '"param={\\"zip\\":\\"%s\\"}"' % (foo)
print(bar)
giving:
"param={\"zip\":\"90210\"}"
Hopefully someone can give you an f-string alternative. I kept running into unallowed "\" in my f-string attempts.
Is it only this?
a = "param={\"zip\":\"64015\"}"
b = a.split('=')
c = eval(b[1])
print(c)
print(c['zip'])
Result:
{'zip': '64015'}
64015
Please note that evaluating (eval()) strings from unknown source may
be dangerous! It may run the code that you are not expecting.
New to python, what am i doing wrong here that it wont print my total out?
second = 2
third = 3
extra = input("what is the extra value?")
total = ("first+second+thrid+extra")
print("total,")
You are printing a string by putting in double quotes
Whereas expression should be like this:
result = first + second + extra
print(result) # without quotes
I currently have to a code in ABAP which contains a String that has multiple words that start with Capital letters/Uppercase and there is no space in-between.
I have to separate it into an internal table like this:
INPUT :
NameAgeAddress
OUTPUT :
Name
Age
Address
Here is the shortest code I could find, which uses a regular expression combined with SPLIT:
SPLIT replace( val = 'NameAgeAddress' regex = `(?!^.)\u` with = ` $0` occ = 0 )
AT ` `
INTO TABLE itab.
So, replace converts 'NameAgeAddress' into 'Name Age Address' and SPLIT puts the 3 words into an internal table.
Details:
(?!^.) to say the next character to find (\u) should not be the first character
\u being any upper case letter
$0 to replace the found string ($0) by itself preceded with a space character
occ = 0 to replace all occurrences
Unfortunately, the SPLIT statement in ABAP does not allow a regex as separator expression. Therefore, we have to use progressive matching, which is a bit awkward in ABAP:
report zz_test_split_capital.
parameters: p_input type string default 'NameAgeAddress' lower case.
data: output type stringtab,
off type i,
moff type i,
mlen type i.
while off < strlen( p_input ).
find regex '[A-Z][^A-Z]*'
in section offset off of p_input
match offset moff match length mlen.
if sy-subrc eq 0.
append substring( val = p_input off = moff len = mlen ) to output.
off = moff + mlen.
else.
exit.
endif.
endwhile.
cl_demo_output=>display_data( output ).
Just for comparison, the following statement would do the job in Perl:
my $input = "NameAgeAddress";
my #output = split /(?=[A-Z])/, $input;
# gives #output = ('Name','Age','Address')
It is easy with using regular expressions. The solution could look like this.
REPORT ZZZ.
DATA: g_string TYPE string VALUE `NameAgeAddress`.
DATA(gcl_regex) = NEW cl_abap_regex( pattern = `[A-Z]{1}[a-z]+` ).
DATA(gcl_matcher) = gcl_regex->create_matcher( text = g_string ).
WHILE gcl_matcher->find_next( ).
DATA(g_match_result) = gcl_matcher->get_match( ).
WRITE / g_string+g_match_result-offset(g_match_result-length).
ENDWHILE.
For when regular expressions are just overkill and plain old ABAP will do:
DATA(str) = 'NameAgeAddress'.
IF str CA sy-abcde.
DATA(off) = 0.
DO.
data(tailstart) = off + 1.
IF str+tailstart CA sy-abcde.
DATA(len) = sy-fdpos + 1.
WRITE: / str+off(len).
add len to off.
ELSE.
EXIT.
ENDIF.
ENDDO.
write / str+off.
ENDIF.
If you do not want to use or cannot use Regex, here another solution:
DATA: lf_input TYPE string VALUE 'NameAgeAddress',
lf_offset TYPE i,
lf_current_letter TYPE char1,
lf_letter_in_capital TYPE char1,
lf_word TYPE string,
lt_word LIKE TABLE OF lf_word.
DO strlen( lf_input ) TIMES.
lf_offset = sy-index - 1.
lf_current_letter = lf_input+lf_offset(1).
lf_letter_in_capital = to_upper( lf_current_letter ).
IF lf_current_letter = lf_letter_in_capital.
APPEND INITIAL LINE TO lt_word ASSIGNING FIELD-SYMBOL(<ls_word>).
ENDIF.
IF <ls_word> IS ASSIGNED. "if input string does not start with capital letter
<ls_word> = <ls_word> && lf_current_letter.
ENDIF.
ENDDO.