[英]How do I trim a string after certain amount of characters appear more then once in Python?
I am trying to scan a string and every time it reads a certain character 3 times, I would like to cut the remaining string 我正在尝试扫描一个字符串,并且每次读取某个字符3次时,我都想剪切剩余的字符串
for example: The string "C:\\Temp\\Test\\Documents\\Test.doc" would turn into "C:\\Temp\\Test\\" 例如:字符串“ C:\\ Temp \\ Test \\ Documents \\ Test.doc”将变成“ C:\\ Temp \\ Test \\”
Every time the string hits "\\" 3 times it should trim the string 字符串每次击中“ \\” 3次时,都应修剪字符串
here is my code that I am working on 这是我正在处理的代码
prefix = ["" for x in range(size)]
num = 0
...
...
for char in os.path.realpath(src):
for x in prefix:
x = char
if x =='\': # I get an error here
num = num + 1
if num == 3:
break
print (num)
print(prefix)
...
...
the os.path.realpath(src)
is the string with with the filepath. os.path.realpath(src)
是带有文件路径的字符串。 The "prefix" variable is the string array that I want to store the trimmed string. “前缀”变量是我要存储修剪后的字符串的字符串数组。
Please let me know what I need to fix or if there is a simpler way to perform this. 请让我知道我需要解决的问题,或者是否有更简单的方法来执行此操作。
Do split
and then slice list to grab required and join
: 先
split
然后分割列表以获取必需的并join
:
s = 'C:\Temp\Test\Documents\Test.doc'
print('\\'.join(s.split('\\')[:3]) + '\\')
# C:\Temp\Test\
Note that \\
(backslash) is an escaping character. 请注意,
\\
(反斜杠)是转义字符。 To specifically mean a backslash, force it to be a backslash by adding a backslash before backslash \\\\
, thereby removing the special meaning of backslash. 要专门表示反斜杠,可以通过在反斜杠
\\\\
之前添加反斜杠来使其强制为反斜杠,从而消除反斜杠的特殊含义。
In python the backslash character is used as an escape character. 在python中,反斜杠字符用作转义字符。 If you do \\n it does a newline, \\t does a tab.
如果您执行\\ n,则执行换行,\\ t进行制表符。 There are many other things such as \\" lets you do a quote in a string. If you want a regular backslash you should do "\\\\"
还有许多其他事情,例如\\“允许您在字符串中加引号。如果要使用常规反斜杠,则应使用” \\\\“
try 尝试
s = "C:\\Temp\\Test\\Documents\\Test.doc"
answer = '\\'.join(s.split('\\', 3)[:3])
Something like this would do.. 这样的事情会做..
x = "C:\Temp\Test\Documents\Test.doc"
print('\\'.join(x.split("\\")[:3])+"\\")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.