Remove first word from string if length is 1 [duplicate] - python

This question already has answers here:
Removing any single letter on a string in python
(6 answers)
Closed 2 years ago.
I want to remove the first character in a string, and the white space after it, only if the first word is one character.
Like this:
input = "A fish"
output = "fish"
Is there a way to do this without turning it into a list first?

You can do this with indexing:
def remove_first(s):
if len(s) < 2:
return s
# if string is letter then a space then trim the first 2 chars
if s[0].isalpha() and s[1].isspace():
return s[2:]
return s
remove_first("A fish") # "fish"
remove_first("fish") # "fish"

Here is how:
text = "A fish"
if text[1] == ' ':
text = text[2:]
print(text)
Output:
fish

Related

How to get the first letter index of a string after spaces in Python? [duplicate]

This question already has answers here:
What is the pythonic way to count the leading spaces in a string?
(7 answers)
Closed last year.
Is there a way to get the first letter index of a string after an n number of spaces?
I know it is easily made with a for loop, but for sake of simplicity, is there a cleaner way?
string_1 = " Hello" # Return 4
string_2 = " Bye" # Return 8
Method strip() cuts spaces before the first and after the last charactes (and multiple inside like x y.
So:
x = ' abc'
x = x.strip()
print(x) # result -> 'abc'
You can use filter, enumerate, and next to stop whevener the condition is met:
string_1 = " Hello"
next(filter(lambda x: x[1]!=' ', enumerate(string_1)))[0]
# 4

Small String that continuously repeated in Big String [duplicate]

This question already has answers here:
Counting longest occurrence of repeated sequence in Python
(5 answers)
Closed 1 year ago.
I am trying to get a length of a Small string that repeats large string continuously in Python
I Tried...
def repeats(string):
for x in range(1, len(string)):
substring = string[:x]
if substring * (len(string)//len(substring))+(substring[:len(string)%len(substring)]) == string:
return "break"
print(len(substring))
But it's long..
Plese Give me your knowledge.
You might be able to use a regex re.findall approach here:
def longest_repeat(x):
matches = re.findall(r'(.+)\1+', x)
matches.sort(key=lambda s: len(s), reverse=True)
if not matches:
return ''
else:
return matches[0]
inp = ["agtcaggtccaggtccgatcgaatac", "agtcgggggggatta", "agtctgcatgac"]
for i in inp:
output = longest_repeat(i)
print(i + ', ' + output)
This prints:
agtcaggtccaggtccgatcgaatac, caggtc
agtcgggggggatta, ggg
agtctgcatgac,

How to cancel new line print in for loop output in python? [duplicate]

This question already has answers here:
How to print without a newline or space
(26 answers)
Closed 2 years ago.
Remember: The , character after our print statement means that our next print statement keeps printing on the same line. Let's filter out the letter 'A' from our string.
phrase = "A bird in the hand..."
Do the following for each character in the phrase.
If char is an 'A' or char is an 'a', print 'X', instead of char. Make sure to include the trailing comma.
Otherwise (else:), please print char, with the trailing comma.
For the above question, I got the below code:
phrase = "A bird in the hand..."
for char in phrase:
if char == 'A' or char =='a':
print('X')
else:
print (char)
The output:
X
b
i
r
d
i
n
t
h
e
h
X
n
d
.
.
.
How do I get the output on one line?
print(value, end="")
BTW, for your task, you can just:
processed = phrase.replace('A', 'x').replace('a', 'x')
print(processed)
Whenever you need an output printed in the same line, all you need to do is to terminate your print function with the argument 'end' in Python3
phrase = "A bird in the hand..."
for char in phrase.lower():
if char =='a':
print('X', end="" )
else: print (char, end="" )
Another way to do this is to concatenate each part of the string together and print it all out at once.
finaloutput = “”
phrase = “A bird in the hand...”
for char in phrase.lower():
if char == “a”:
finaloutput += X
else:
finaloutput += char
print(finaloutput)

How to replace characters in a string of 0's and 1's by other characters [duplicate]

This question already has answers here:
Best way to replace multiple characters in a string?
(16 answers)
Closed 3 years ago.
I am trying to write a function that takes a string of 1 and 0 and replaces the 1 with "." and the 0 with "_"
I am not sure how to store the new string and print it afterwards
def transform (x):
text = ''
for i in range(x):
if i == 1:
i = "."
text += i
else:
i = "_"
text += i
return text
transform(10110)
This is one way: Loop over the string directly and then add the . or _ based on the if statement. Make sure you use i == '1' because your input is a string. You don't need to modify the value of i inside the if statements.
def transform(x):
text = ''
for i in x:
if i == '1':
text += "." # directly add the `.`
else:
text += "_" # directly add the `_`
return text
transform('11001010') # call the function
# print (transform('11001010'))
# '..__._._'

How do you sort integers in a string [duplicate]

This question already has answers here:
Split a string with unknown number of spaces as separator in Python [duplicate]
(6 answers)
Closed 4 years ago.
This function takes one string parameter. Assume the string will be a series of integers separated by spaces. Ignore any extra whitespace. The empty string or a whitespace string return the empty string. Otherwise, the function returns a string with the argument’s integers
separated by spaces but now in sorted order. Do not check for invalid strings. For instance, if the argument is 43 -1 17, the function returns -1 17 43.`
it does not work in a situation where the input is \t42 4 -17 \n
def sort_int_string(string):
strlist = string.split(' ')
new = []
for value in strlist:
value2 = int(value)
new.append(value2)
new = sorted(new)
strlist2 = []
for number in new:
number = str(number)
strlist2.append(number)
final = ' '.join(strlist2)
return final
based on your comment, change the line:
strlist = string.split(' ')
to
strlist = string.split()
That should work because when sep is not specified, it defaults to white space. [ \t\n\r\f\v] are all white spaces.
#VanTan has explained the problem with your code. But you can also use:
x = '43 -1 17'
res = ' '.join(map(str, sorted(map(int, x.split()))))
# '-1 17 43'
This list comprehension should handle the whitespace you are encountering:
s = "\t42 4 -17 \n"
sorted([int(x) for x in " ".join(s.split()).split()])
[-17, 4, 42]

Categories