I need help figuring out how to do these following thigns for a string
If the character is an uppercase: change it to lowercase with '!' sign on its both sides (e.g. 'M' --> '!m!');
If the character is a lowercase: change it to uppercase with '!' sign on its both sides (e.g. 'm' --> '!M!');
If the character is a digit: cube the digit, i.e. raise to the power of 3 (e.g. '5' --> '125');
If the character is a blank space: replace it with '$' symbol;
Otherwise: keep it as it is.
I don't know where to start, besides a possible loop statement.
You can do this:
string = "Mm5 #"
new_string = ""
for char in string:
if char.isupper():
new_string += "!" + char.lower() + "!"
elif char.islower():
new_string += "!" + char.upper() + "!"
elif char.isdigit():
new_string += str(int(char) ** 3)
elif char == " ":
new_string += "$"
else:
new_string += char
print(new_string)
>> !m!!M!125$#
Iterate over the string.
According to the transformation rules, transforms each character in the string.
Returns the new string.
def convertString(input):
output = ''
for char in input:
if char.isupper():
char = '!' + char.lower() + '!'
output += char
elif char.islower():
char = '!' + char.upper() + '!'
output += char
elif char.isdigit():
char = int(char) * int(char) * int(char)
char = str(char)
output += char
elif char.isspace():
char = '$'
output += char
else:
char = char
output += char
return output
if __name__ == '__main__':
input = 'Mm 5:)'
output = convertString(input)
print(output)
Output
!m!!M!$125:)
Here's answer for your question. It is in Kotlin but you can get the logic and convert it in Python.
fun main(){
println("Enter String: ")
val str = readln()
var newString = ""
for (s in str){
when{
s.isDigit() -> newString += (s.digitToInt() * s.digitToInt() * s.digitToInt())
s.isLowerCase() -> newString += "!" + s.uppercase() + "!"
s.isUpperCase() -> newString += "!" + s.lowercase() + "!"
s == ' ' -> newString += "$"
}
}
println("String formatted as: $newString")
}
Related
I want to split my string using python 3+ which is having commas. I don't want string to split based on commas inside brackets.
For example:-
cstr = 'animal_tiger,(CAST(SUBSTR(TRIM(replace(MAX(tigers_name),"Body Parts",'')),1,3) AS INT))'
I want to split this into two string elements.
I tried splitting based on commas but it is taking inside commas as well.
import re
import csv
from StringIO import StringIO
cstr = 'animal_tiger,(CAST(SUBSTR(TRIM(replace(MAX(tigers_name),"Body Parts",'')),1,3) AS INT))'
b = re.split(r',(?=")', cstr)
print(b)
c = re.split(''',(?=(?:[^'"]|'[^']*'|"[^"]*")*$)''', cstr)
print(c)
data = StringIO(cstr)
reader = csv.reader(data, delimiter=';')
for row in reader:
print(row)
def split_with_commas_outside_of_quotes(string):
arr = []
start, flag = 0, False
for pos, x in enumerate(string):
if x == '(' and x == ')':
flag= not(flag)
if flag == False and x == ',':
arr.append(string[start:pos])
start = pos+1
arr.append(string[start:pos])
return arr
print(split_with_commas_outside_of_quotes(cstr))
print(cstr.replace('(','$')).replace(')','#').split(',')
Expected result is splitting of string into two different strings of list that is:-
outputlist - ['animal_tiger','(CAST(SUBSTR(TRIM(replace(MAX(tigers_name),"Body Parts",'')),1,3) AS INT))']
remember the length of the list is 2.
Here you go. Use this function:
def split_with_commas_outside_of_quotes(string):
arr = []
bracketCount = 0
currentItem = ""
for i in range(len(string)):
if i == len(string)-1:
currentItem += string[i]
arr.append(currentItem)
elif string[i] == "(":
bracketCount += 1
currentItem += string[i]
elif string[i] == ")":
bracketCount -= 1
currentItem += string[i]
elif bracketCount == 0 and string[i] == ",":
arr.append(currentItem)
currentItem = ""
else:
currentItem += string[i]
return arr
cstr = 'animal_tiger,(CAST(SUBSTR(TRIM(replace(MAX(tigers_name),"Body Parts",'')),1,3) AS INT))'
print(split_with_commas_outside_of_quotes(cstr))
Output:
['animal_tiger', '(CAST(SUBSTR(TRIM(replace(MAX(tigers_name),"Body Parts",)),1,3) AS INT))']
You can use split():
data = """animal_tiger,(CAST(SUBSTR(TRIM(replace(MAX(tigers_name),"Body Parts",'')),1,3) AS INT))"""
data.split(',', 1)
>>> ['animal_tiger',
'(CAST(SUBSTR(TRIM(replace(MAX(tigers_name),"Body Parts",\'\')),1,3) AS INT))']
I'm trying to loop through a directory of image files and match the file's name to corresponding title string so that the path can be inserted into a database. What i have below works for about 90% of the files, but my string cleaning method is imperfect. Im looking for a smarter way of doing this. Thanks for your time.
filename example : "2020_Super_Baseball_usa.jpg"
title string example : "2020 Super Baseball"
def string_cleaner(string_one):
'''filter non alpha chars from filename'''
filter_by= ":*/?-_.,'!'"
new_string= ""
for char in filter_by:
for letter in string_one:
if letter == char:
if new_string == "":
new_string = string_one.replace(char, "")
else:
new_string = new_string.replace(char, "")
return new_string
def matcher(string):
'''matches title string to filename and returns full path'''
temp_path = ""
tempfilename = ""
path = "C:\\Users\\USER\\Desktop\\pyscripts\\web- scraping\\SNES_DB_Scrape\\snes\\"
for file in os.listdir(path):
tempfilename = string_cleaner(file[:-7]).lower().lstrip().rstrip()
if string.lower().lstrip() == tempfilename :
temp_path = os.path.join(path, file)
return temp_path
for name in nameList:
path = matcher(name)
print("Name is: " + name + '\n' + "path is : " + path)
considering your filename and title example, you can try below code:
filename = "2020_Super_Baseball_usa.jpg"
title = "2020 Super Baseball"
def string_cleaner(string_one):
'''filter non alpha chars from filename'''
new_string = ""
for char in string_one:
if char.isalnum(): #checking if string_one character if alphanumeric
new_string = new_string + char
elif char == '_':
new_string = new_string + " "
return new_string
temp = string_cleaner(filename[:-7])
#print(temp) #check output of string_cleaner function
if temp.lower().lstrip().rstrip() == title.lower().lstrip():
print("match")
I'm trying to store substrings of letters in 's' that are in alphabetical order in a list
s = 'azcbobobegghakl'
string = ''
List = []
i = -1
for letter in s:
if letter == s[0]:
string += letter
elif letter >= s[i]:
string += letter
elif letter < s[i]:
List.append(string)
string = letter
i += 1
print(List)
My expected result:
['az', 'c', 'bo', 'bo', 'beggh', 'akl']
And my actual Output:
['az', 'c', 'bo', 'bo']
Firstly, your first if statement is incorrect. It should be if i == -1:. Because of this bug, you are ignoring the second a character in s.
Secondly, at the end of the string you don't add what's left of string into List.
As such, the following is what you want:
s = 'azcbobobegghakl'
string = ''
List = []
i = -1
for letter in s:
if i == -1:
string += letter
elif letter >= s[i]:
string += letter
elif letter < s[i]:
List.append(string)
string = letter
i += 1
List.append(string)
print(List)
An example is available here.
s1 = input("enter 1st string: ")
s2 = input("enter 2nd string: ")
if s2 in s1:
print("found")
else:
print("not found")
simply i want to say if i give some input to s1 and not give anything as input to s2 and press enter, Output of this code print "found"
which is wrong because blank is not in my string s1, So why it is happening? and how to correct it?
Every string contains the empty string so '' in 'anything' is always True.
Every string always contains the empty string.
i = 'anything'.count('')
print(i)
# 9
As you can see, between every letter and before and after the string, there is 'the empty string'.
In your example, you can ensure that a non-empty string is entered like so:
while(True):
s1 = input("enter 1st string: ")
if s1 != '':
break
while(True):
s2 = input("enter 2nd string: ")
if s2 != '':
break
if s2 in s1:
print("found")
else:
print("not found")
Also note:
s = '' + 'a' + '' + 'n'+ '' + 'y' + '' + 't' + '' + 'h' + '' + 'i' + '' + 'n' + '' + 'g' + ''
print(s == 'anything')
# True
print(s.count('')
# 9
Adding more empty strings does not have any effect.
s += ''
print(s.count('')
# 9
counter = 0
sentence = 'Hello World'
split = str.split(sentence)
for str in split:
c = split[counter]
scramble = c[4] + c[0] + c[3] + c[1] + c[2]
counter += 1
print (scramble)
The program should rearrange each word in a string into a specific pattern but I cannot figure out how to print the scrambled text onto the same line.
Here you go
counter = 0
sentence = 'Hello World'
split = str.split(sentence)
for str in split:
c = split[counter]
scramble = c[4] + c[0] + c[3] + c[1] + c[2]
counter += 1
print (scramble, end=" ")
The print function accepts an end parameter which defaults to "\n". Setting it to an empty string prevents it from issuing a new line at the end of the line.