Python – 水平和垂直字符串相互转换
给定一个字符串,如果水平则转换为垂直,反之亦然。
Input : test_str = ‘geeksforgeeks’
Output : g
e
e
k
s
Explanation : Horizontal String converted to Vertical.
Input : test_str = g
e
e
k
s
Output : ‘geeks’
Explanation : Vertical String converted to Horizontal.
方法 #1 : [水平到垂直] 使用循环 + “\n”
在此,我们在每个字符之后添加字符,以便每个元素在下一行呈现。
Python3
# Python3 code to demonstrate working of
# Interconvert Horizontal and Vertical String
# using [Horizontal to Vertical] using loop + "\n"
# initializing string
test_str = 'geeksforgeeks'
# printing original String
print("The original string is : " + str(test_str))
# using loop to add "\n" after each character
res = ''
for ele in test_str:
res += ele + "\n"
# printing result
print("The converted string : " + str(res))
Python3
# Python3 code to demonstrate working of
# Interconvert Horizontal and Vertical String
# using [Vertical to Horizontal] using replace() + "\n"
# initializing string
test_str = 'g\ne\ne\nk\ns\nf\no\nr\ng\ne\ne\nk\ns\n'
# printing original String
print("The original string is : " + str(test_str))
# using replace() + "\n" to solve this problem
res = test_str.replace("\n", "")
# printing result
print("The converted string : " + str(res))
输出
The original string is : geeksforgeeks
The converted string : g
e
e
k
s
f
o
r
g
e
e
k
s
方法 #2 : [垂直到水平] 使用 replace() + “\n”
在此,我们通过替换为空字符串来删除“\n”来执行转换任务。
Python3
# Python3 code to demonstrate working of
# Interconvert Horizontal and Vertical String
# using [Vertical to Horizontal] using replace() + "\n"
# initializing string
test_str = 'g\ne\ne\nk\ns\nf\no\nr\ng\ne\ne\nk\ns\n'
# printing original String
print("The original string is : " + str(test_str))
# using replace() + "\n" to solve this problem
res = test_str.replace("\n", "")
# printing result
print("The converted string : " + str(res))
输出
The original string is : g
e
e
k
s
f
o
r
g
e
e
k
s
The converted string : geeksforgeeks